#!/bin/sh
#/ Usage: ghe-restore-settings <host>
#/ Restore settings from a snapshot to the given <host>.
set -e

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

# Show usage and bail with no arguments
[ -z "$*" ] && print_usage

# 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 settings ..."
if [ "$GHE_VERSION_MAJOR" -ge 2 ]; then
  # 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
else
    ( cat "$GHE_RESTORE_SNAPSHOT_PATH/settings.json" && echo ) |
    ghe-ssh "$GHE_HOSTNAME" -- '/usr/bin/env GHEBUVER=2 ghe-import-settings' 1>&3
fi

# Bail out if we're restoring against a pre-2.x appliance. Everything below is
# supported by v2.0 appliances only.
if [ "$GHE_VERSION_MAJOR" -lt 2 ]; then
    exit 0
fi

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

# Restore management console password hash if present.
if [ -f "$GHE_RESTORE_SNAPSHOT_PATH/manage-password" ]; then
    echo "Restoring management console password ..."
    cat "$GHE_RESTORE_SNAPSHOT_PATH/manage-password" |
    ghe-ssh "$GHE_HOSTNAME" -- "ghe-import-passwords"
fi
