#!/bin/sh
#/ Usage: ghe-restore-backup [-c] <hostname>

GIT_BACKUP_VERSION="3.0.0"

# Exit immediately if a command exits with a non-zero status.
set -e
set -x

# Assume the current directory is the root.
GHE_SECURE_BACKUP_ROOT="$(pwd)"

# The backup config file. This may be set in the environment.
: ${GHE_SECURE_BACKUP_CONFIG:="$GHE_SECURE_BACKUP_ROOT/../etc/ghe-secure-backup.conf"}

# Source in the backup config file from the local working copy location first
# and then falling back to the system location.
config_found=false
for f in "$GHE_SECURE_BACKUP_CONFIG" "/opt/twitch/ghe-secure-backup/etc/ghe-secure-backup.conf"; do
    if [ -f "$f" ]; then
        GHE_SECURE_BACKUP_CONFIG="$f"
        . "$GHE_SECURE_BACKUP_CONFIG"
        config_found=true
        break
    fi
done

# Check that the config file exists before we source it in.
if ! $config_found; then
    echo "Error: No GHE secure backup configuration file found. Tried:" 1>&2
    echo " - $GHE_SECURE_BACKUP_CONFIG" 1>&2
    echo " - /opt/twitch/ghe-secure-backup/etc/ghe-secure-backup.conf" 1>&2
    exit 2
fi

restore_settings=false
while true; do
  case "$1" in
    -c|--config)
      restore_settings=true
      shift
      ;;
    -*)
      echo "Error: invalid argument: '$1'" 1>&2
      exit 1
      ;;
    *)
      if [ -n "$1" ]; then
        GHE_RESTORE_HOST="$1"
        shift
      else
        break
      fi
      ;;
  esac
done


# Check that the host argument is passed
if [ -z "$GHE_RESTORE_HOST" ]; then
    echo "Error: No host to restore backup specified in arguments." 1>&2
    exit 2
fi

echo ">>> Enabling maintenance mode in $GHE_RESTORE_HOST (`date`)"
ssh -p 122 admin@$GHE_RESTORE_HOST ghe-maintenance -s

if $restore_settings; then
    echo ">>> Restoring backup to $GHE_RESTORE_HOST, including settings... (`date`)"
    github-backup-utils-v$GIT_BACKUP_VERSION/bin/ghe-restore -fc $GHE_RESTORE_HOST
else
    echo ">>> Restoring backup to $GHE_RESTORE_HOST, excluding settings... (`date`)"
    github-backup-utils-v$GIT_BACKUP_VERSION/bin/ghe-restore -f $GHE_RESTORE_HOST
fi

echo ">>> Disabling maintenance mode in $GHE_RESTORE_HOST (`date`)"
ssh -p 122 admin@$GHE_RESTORE_HOST ghe-maintenance -u
