#!/usr/local/bin/bash
#/ Usage: ghe-backup-settings
#/ Restore settings from a snapshot to the given <host>.
set -e

# Bring in the backup configuration
. $( dirname "${BASH_SOURCE[0]}" )/ghe-backup-config

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

bm_start "$(basename $0)"

# 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

    if ghe-ssh "$host" -- "test -f $GHE_REMOTE_DATA_USER_DIR/common/idp.crt"; then
      echo "* Transferring SAML keys ..." 1>&3
      ghe-ssh $host -- sudo tar -C $GHE_REMOTE_DATA_USER_DIR/common/ -cf - "idp.crt saml-sp.p12" > saml-keys.tar
    fi
fi

if [ "$GHE_BACKUP_STRATEGY" = "cluster" ]; then
  echo "* Transferring cluster configuration ..." 1>&3
  if ! ghe-ssh "$host" -- "sudo cat $GHE_REMOTE_CLUSTER_CONF_FILE 2>/dev/null" > cluster.conf; then
    echo "Error: Enterprise Cluster is not configured yet, backup will fail" >&2
    exit 1
  fi
else
  if ghe-ssh "$host" -- "sudo cat $GHE_REMOTE_DATA_USER_DIR/common/uuid 2>/dev/null" > uuid; then
    echo "* Transferring UUID ..." 1>&3
  fi
fi

bm_end "$(basename $0)"
