#!/usr/bin/env bash
#/ Usage: ghe-restore-actions <host>
#/ Restore additional Actions files from an rsync snapshot.
#/
#/ Note: This script typically isn't called directly. It's invoked by the
#/ ghe-restore command.
set -e

# Bring in the backup configuration
# shellcheck source=share/github-backup-utils/ghe-backup-config
. "$( dirname "${BASH_SOURCE[0]}" )/ghe-backup-config"

# Show usage and bail with no arguments
[ -z "$*" ] && print_usage

bm_start "$(basename $0)"

# Grab host arg
GHE_HOSTNAME="$1"

# The snapshot to restore should be set by the ghe-restore command but this lets
# us run this script directly.
: ${GHE_RESTORE_SNAPSHOT:=current}

# Path to snapshot dir we're restoring from
GHE_RESTORE_SNAPSHOT_PATH="$GHE_DATA_DIR/$GHE_RESTORE_SNAPSHOT"

port=$(ssh_port_part "$GHE_HOSTNAME")
host=$(ssh_host_part "$GHE_HOSTNAME")

# No need to restore anything, early exit
if [ ! -d "$GHE_RESTORE_SNAPSHOT_PATH/actions" ]; then
  log_warn "Warning: Actions backup missing. Skipping ..."
  exit 0
fi

# Perform a host-check and establish GHE_REMOTE_XXX variables.
ghe_remote_version_required "$host"

# Transfer all Actions data from the snapshot to the user data directory using rsync.
ghe_verbose "* Transferring Actions files to $host ..."

ghe-ssh -p "$port" "$host" -- sudo mkdir -p "$GHE_REMOTE_DATA_USER_DIR/actions"
ghe-ssh -p "$port" "$host" -- sudo chown -R actions:actions "$GHE_REMOTE_DATA_USER_DIR/actions"
log_rsync "BEGIN: actions rsync" 1>&3
ghe-rsync -arvHR --delete \
  -e "ghe-ssh -p $port" \
  --rsync-path='sudo -u actions rsync' \
  "$GHE_RESTORE_SNAPSHOT_PATH/actions/./" \
  "$host:$GHE_REMOTE_DATA_USER_DIR/actions/" 1>&3
log_rsync "END: actions rsync" 1>&3
# Restore Actions settings.
ghe_verbose "* Restoring Actions settings to $host ..."

# Setup the database logins.
ghe_verbose "* Restoring database logins and users to $host ..."

ghe-ssh -p "$port" "$host" -- ghe-actions-console -s mps -c "Repair-DatabaseLogins"
ghe-ssh -p "$port" "$host" -- ghe-actions-console -s token -c "Repair-DatabaseLogins"
ghe-ssh -p "$port" "$host" -- ghe-actions-console -s actions -c "Repair-DatabaseLogins"

if [ ! -z "$(find "$GHE_DATA_DIR/$GHE_RESTORE_SNAPSHOT/mssql/" -maxdepth 1 -name 'ArtifactCache_Configuration*.bak')" ]; then
  ghe-ssh -p "$port" "$host" -- ghe-actions-console -s artifactcache -c "Repair-DatabaseLogins"
  else
   log_info "ArtifactCache is not present in mssql backup. Skipping Repair-DatabaseLogins for it."
fi

bm_end "$(basename $0)"
