#!/usr/bin/env bash
#/ Usage: ghe-restore-settings <host>
#/ Restore settings from a snapshot to the given <host>.
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"

# 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}

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

echo "Restoring license ..."
ghe-ssh "$GHE_HOSTNAME" -- 'ghe-import-license' < "$GHE_RESTORE_SNAPSHOT_PATH/enterprise.ghl" 1>&3

echo "Restoring settings and applying configuration ..."

# Restore external MySQL password if running external MySQL DB.
restore-secret "external MySQL password" "external-mysql-password" "secrets.external.mysql"

# work around issue importing settings with bad storage mode values
( cat "$GHE_RESTORE_SNAPSHOT_PATH/settings.json" && echo ) |
  sed 's/"storage_mode": "device"/"storage_mode": "rootfs"/' |
  ghe-ssh "$GHE_HOSTNAME" -- '/usr/bin/env GHEBUVER=2 ghe-import-settings' 1>&3

# Restore management console password hash if present.
restore-secret "management console password" "manage-password" "secrets.manage"

# Restore SAML keys if present.
if [ -f "$GHE_RESTORE_SNAPSHOT_PATH/saml-keys.tar" ]; then
  echo "Restoring SAML keys ..."
  cat "$GHE_RESTORE_SNAPSHOT_PATH/saml-keys.tar" |
  ghe-ssh "$GHE_HOSTNAME" -- "sudo tar -C $GHE_REMOTE_DATA_USER_DIR/common/ -xf -"
fi

# Restore CA certificates if present.
if [ -f "$GHE_RESTORE_SNAPSHOT_PATH/ssl-ca-certificates.tar" ]; then
  echo "Restoring CA certificates ..."
  cat "$GHE_RESTORE_SNAPSHOT_PATH/ssl-ca-certificates.tar" |
  ghe-ssh "$GHE_HOSTNAME" -- "ghe-import-ssl-ca-certificates"
fi

bm_end "$(basename $0)"
