#!/bin/sh
#/ Usage: ghe-backup-settings
#/ 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

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

# Grab the host
host="$GHE_HOSTNAME"

# Create the snapshot directory if needed and change into it.
mkdir -p "$GHE_SNAPSHOT_DIR"
cd "$GHE_SNAPSHOT_DIR"

echo "* Transferring settings data ..." 1>&3
ghe-ssh "$host" -- 'ghe-export-settings' > settings.json

echo "* Transferring license data ..." 1>&3
comm="cat '$GHE_REMOTE_LICENSE_FILE'"
[ "$GHE_VERSION_MAJOR" -ge 2 ] && comm="sudo $comm"
ghe-ssh "$host" -- "$comm" > enterprise.ghl

if [ "$GHE_VERSION_MAJOR" -ge 2 ]; then
    echo "* Transferring management console password ..." 1>&3
    manage_password_file="$GHE_REMOTE_DATA_USER_DIR/common/manage-password"
    if echo "sudo cat '$manage_password_file' 2>/dev/null || true" |
       ghe-ssh "$host" -- /bin/sh > manage-password+
    then
        if [ -n "$(cat manage-password+)" ]; then
            mv manage-password+ manage-password
        fi
    else
        unlink manage-password+
    fi
fi
