#!/usr/local/bin/bash
#/ Usage: ghe-backup-live-migrations

set -e

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

trap_errors

bm_start "$(basename $0)"

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

user="${host%@*}"
[ "$user" = "$host" ] && user="admin"

backup_dir="${GHE_SNAPSHOT_DIR}/live-upgrade"

LIVE_UPGRADE_PATH="$(ghe-ssh -p "${port}" "${mysql_master}" -- 'ghe-config --default "" live-upgrade.working-path')"
if [ -z "$LIVE_UPGRADE_PATH" ]; then
  ghe_verbose "live-upgrade.working-path is not set. Skipping ..."
  exit 0
fi

ssh_config_file_opt=
tempdir=$(mktemp -d -t backup-utils-restore-XXXXXX)
opts="$GHE_EXTRA_SSH_OPTS"

if [ "$GHE_BACKUP_STRATEGY" = "cluster" ]; then
  mysql_master=$(ghe-ssh "$GHE_HOSTNAME" -- 'ghe-config cluster.mysql-master')
  if [ -z $mysql_master ]; then
    echo "Something is wrong with configuration: cluster.mysql-master not found" >&2
    exit 2
  fi

  ssh_config_file="$tempdir/ssh_config"
  ssh_config_file_opt="-F $ssh_config_file"
  opts="$opts -o UserKnownHostsFile=/dev/null -o StrictHostKeyChecking=no -o PasswordAuthentication=no"
  ghe-ssh-config "$GHE_HOSTNAME" "$mysql_master" > "$ssh_config_file"
else
  mysql_master=$host
fi

mkdir -p "${backup_dir}"

cleanup() {
  [ -d "$tempdir" ] && rm -rf "$tempdir"
}
trap_full_cleanup

# Transfer all live-upgrade data from the user data directory using rsync.
ghe_verbose "* Transferring live-upgrade files from ${mysql_master} ..."

rsync_command="ghe-rsync --archive \
  -e \"ssh -q $opts -p $port $ssh_config_file_opt -l $user\" \
  \"${mysql_master}:${LIVE_UPGRADE_PATH}/\" \
  \"${backup_dir}\""

run_rsync "$rsync_command" "live-upgrade"

bm_end "$(basename $0)"