#!/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"

# Test setting should by default return available
ghe_license_available() {
  if [ -z "$GHE_TEST_REMOTE_VERSION" ]; then
    ghe-ssh "$GHE_HOSTNAME" -- "test -e /usr/local/bin/ghe-license";
  else
    return 0
  fi
}

log_info "Restoring license ..."
# 3.13 bundles all the license related scripts into a single one, with added security checks and features.
# Either one of the scripts will exist.
if ghe_license_available ; then
  # Restore the license despite it being invalid, backup restore is not the place to fail on an invalid license.
  ghe-ssh "$GHE_HOSTNAME" -- 'ghe-license check --pipe' < "$GHE_RESTORE_SNAPSHOT_PATH/enterprise.ghl" || true 1>&3
  ghe-ssh "$GHE_HOSTNAME" -- 'ghe-license import --pipe --skip-checks' < "$GHE_RESTORE_SNAPSHOT_PATH/enterprise.ghl" 1>&3
else 
  ghe-ssh "$GHE_HOSTNAME" -- 'ghe-import-license' < "$GHE_RESTORE_SNAPSHOT_PATH/enterprise.ghl" 1>&3
fi

log_info "Restoring settings and applying configuration ..."

# 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 SAML keys if present.
if [ -f "$GHE_RESTORE_SNAPSHOT_PATH/saml-keys.tar" ]; then
  log_info "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
  log_info "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)"
