#!/bin/sh
#/ Usage: ghe-restore-userdata <dirname> <host>
#/ Restore a special user data directory via rsync. This is used
#/ for a number of different simple datastores kept under /data/user on the
#/ remote appliance, including: hookshot, alambic_assets, and pages data.
set -e

# Bring in the backup configuration
cd $(dirname "$0")/../..
. share/github-backup-utils/ghe-backup-config

# Show usage and bail with no arguments
[ $# -lt 2 ] && print_usage

# Grab userdata directory name and host args
dirname="$1"
GHE_HOSTNAME="$2"

# Verify rsync is available.
if ! rsync --version 1>/dev/null 2>&1; then
    echo "Error: rsync not found." 1>&2
    exit 1
fi

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

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

# Transfer data from the latest snapshot to the GitHub instance in a single
# rsync invocation.
if [ -d "$GHE_DATA_DIR/$GHE_RESTORE_SNAPSHOT/$dirname" ]; then
  ghe-rsync -avz --delete \
      -e "ghe-ssh -p $(ssh_port_part "$GHE_HOSTNAME")" \
      --rsync-path="sudo -u git rsync" \
      "$GHE_DATA_DIR/$GHE_RESTORE_SNAPSHOT/$dirname/" \
      "$(ssh_host_part "$GHE_HOSTNAME"):$GHE_REMOTE_DATA_USER_DIR/$dirname" 1>&3
fi
