#!/usr/bin/env bash
#/ Usage: ghe-restore-repositories-gist <host>
#/ Restore repositories from an rsync snapshot of all Git repository data.
#/
#/ 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}

# Find the gists to restore
gist_paths=$(cd $GHE_DATA_DIR/$GHE_RESTORE_SNAPSHOT/  && find repositories -mindepth 6 -maxdepth 7 -name \*.git | grep gist | cut -d / -f2-)

# No need to restore anything, early exit
if [ -z "$gist_paths" ]; then
  echo "Warning: Gist backup missing. Skipping ..."
  exit 0
fi

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

# Generate SSH config for forwarding
# Split host:port into parts
port=$(ssh_port_part "$GHE_HOSTNAME")
host=$(ssh_host_part "$GHE_HOSTNAME")

# Add user / -l option
user="${host%@*}"
[ "$user" = "$host" ] && user="admin"

hostnames=$host
tempdir=$(mktemp -d -t backup-utils-restore-XXXXXX)
remote_tempdir=$(ghe-ssh "$GHE_HOSTNAME" -- mktemp -d -t backup-utils-restore-XXXXXX)
ssh_config_file_opt=
opts="$GHE_EXTRA_SSH_OPTS"
tmp_list=$tempdir/tmp_list
remote_tmp_list=$remote_tempdir/remote_tmp_list
to_restore=$tempdir/to_restore
remote_to_restore=$remote_tempdir/remote_to_restore
routes_list=$tempdir/routes_list
remote_routes_list=$remote_tempdir/remote_routes_list
remote_warnings=$remote_tempdir/gist_warnings

if $CLUSTER; then
  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"
  hostnames=$(ghe-cluster-nodes "$GHE_HOSTNAME" "git-server")
  ghe-ssh-config "$GHE_HOSTNAME" "$hostnames" > "$ssh_config_file"
fi

cleanup() {
  ghe-ssh "$GHE_HOSTNAME" -- rm -rf $tempdir
  rm -rf $tempdir
}
trap cleanup EXIT

# Build a list of gist paths to send to the server to calculate
# the restore routes, something like:
#
# a/a8/3f/02/gist
# a/a8/bc/8d/gist
# a/a5/06/81/gist
# a/a5/84/6f/gist
# a/a5/e0/01/gist
# ...
#
# One network path per line.
bm_start "$(basename $0) - Building gist list"
OLDIFS=$IFS; IFS=$'\n'
for path in $gist_paths; do
  ghe_verbose "* Adding gist $path to the list of networks to send"
  echo $path
done > $tmp_list
IFS=$OLDIFS
bm_end "$(basename $0) - Building gist list"

# The server returns a list of routes:
#
# a/a8/3f/02/gist/gist_id.git dgit-node3 dgit-node2 dgit-node4
# a/a8/bc/8d/gist/gist_id.git dgit-node3 dgit-node2 dgit-node4
# a/a5/06/81/gist/gist_id.git dgit-node3 dgit-node2 dgit-node4
# a/a5/84/6f/gist/gist_id.git dgit-node1 dgit-node2 dgit-node4
# a/a5/e0/01/gist/gist_id.git dgit-node1 dgit-node2 dgit-node3
# ...
#
# One route per line.
#
# NOTE: The route generation is performed on the appliance as it is considerably
# more performant than performing over an SSH pipe.
#
bm_start "$(basename $0) - Transferring gist list"
cat $tmp_list | ghe-ssh "$GHE_HOSTNAME" -- sponge $remote_tmp_list
cat $tmp_list | ghe_debug
bm_end "$(basename $0) - Transferring gist list"

bm_start "$(basename $0) - Generating routes"
echo "cat $remote_tmp_list | github-env ./bin/gist-cluster-restore-routes > $remote_routes_list" | ghe-ssh "$GHE_HOSTNAME" -- /bin/bash
ghe-ssh "$GHE_HOSTNAME" -- cat $remote_routes_list | ghe_debug
bm_end "$(basename $0) - Generating routes"

bm_start "$(basename $0) - Transferring routes"
ghe-ssh "$GHE_HOSTNAME" -- gzip -c $remote_routes_list | gzip -d > $routes_list
cat $routes_list | ghe_debug
bm_end "$(basename $0) - Transferring routes"

bm_start "$(basename $0) - Processing routes"
cat $routes_list | awk -v tempdir="$tempdir" '{ for(i=2;i<=NF;i++){ print $1 > (tempdir"/"$i".rsync") }}'
cat $routes_list | awk '{ n = split($1, p, "/"); i = p[n]; sub(/\.git/, "", i); printf i " /data/repositories/" $1; $1=""; print $0}' > $to_restore
ghe_debug "\n$(find "$tempdir" -maxdepth 1 -name '*.rsync')"
bm_end "$(basename $0) - Processing routes"

if [ -z "$(find "$tempdir" -maxdepth 1 -name '*.rsync')" ]; then
  echo "Warning: no routes found, skipping gists restore ..."
  exit 0
fi

# rsync all the gist repositories
bm_start "$(basename $0) - Restoring gists"
for file_list in $tempdir/*.rsync; do
  if $CLUSTER; then
    server=$(basename $file_list .rsync)
  else
    server=$host
  fi
  ghe_verbose "* Transferring gists to $server"
  ghe-rsync -avrR --delete \
    -e "ssh -q $opts -p $port $ssh_config_file_opt -l $user" \
    --rsync-path="sudo -u git rsync" \
    --files-from=$file_list \
    "$GHE_DATA_DIR/$GHE_RESTORE_SNAPSHOT/repositories/./" \
    "$server:$GHE_REMOTE_DATA_USER_DIR/repositories/" 1>&3
done
bm_end "$(basename $0) - Restoring gists"

if $CLUSTER; then
  bm_start "$(basename $0) - Finalizing routes"
  ghe_verbose "Finalizing routes"
  cat $to_restore | ghe-ssh "$GHE_HOSTNAME" -- sponge $remote_to_restore
  ghe-ssh "$GHE_HOSTNAME" -- /bin/bash >&3 <<EOF
    split -l 1000 $remote_to_restore $remote_tempdir/chunk
    chunks=\$(find $remote_tempdir/ -name chunk\*)
    parallel -i /bin/sh -c "cat {} | github-env ./bin/gist-cluster-restore-finalize 2>>$remote_warnings" -- \$chunks
EOF
  bm_end "$(basename $0) - Finalizing routes"
fi

restore_warnings="$(ghe-ssh "$GHE_HOSTNAME" -- cat "$remote_warnings" 2>/dev/null || true)"
if [ -n "$restore_warnings" ]; then
  echo "Warning: One or more Gists failed to restore successfully. Please contact GitHub Enterprise Support for assistance."
  echo "$restore_warnings"
fi

bm_end "$(basename $0)"
