#!/usr/bin/env bash
#/ Usage: ghe-restore-mysql <host>
#/ Restore MySQL backup to a GitHub instance.
#/
#/ Note: This script typically isn't called directly. It's invoked by the
#/ ghe-restore command when the rsync strategy is used.
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 the remote version in GHE_REMOTE_VERSION.
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}
export GHE_RESTORE_SNAPSHOT

# The directory holding the snapshot to restore
GHE_RESTORE_SNAPSHOT_PATH="$GHE_DATA_DIR/$GHE_RESTORE_SNAPSHOT"

if is_external_database_snapshot; then
  if [ -n "$EXTERNAL_DATABASE_RESTORE_SCRIPT" ]; then
    $EXTERNAL_DATABASE_RESTORE_SCRIPT
    # ensure that haproxy and mysql are ready to accept connections before continuing
    if ! ghe-ssh "$GHE_HOSTNAME" -- "/usr/local/share/enterprise/ghe-service-wait-mysql"; then
      error_message "Failed to connect to MySQL service!"
      exit 2
    fi
    bm_end "$(basename $0)"
    exit 0
  else
    if is_binary_backup "$GHE_RESTORE_SNAPSHOT_PATH"; then
      log_error "Error: Restore of a binary backup to appliance with an external database configured is not supported. Please provide a custom external database restore script with EXTERNAL_DATABASE_RESTORE_SCRIPT"
      exit 1
    fi 

    if ! is_default_external_database_snapshot; then
      log_error "Error: Backup was not taken with a GitHub provided backup strategy. You must provide a custom restore script for this backup using EXTERNAL_DATABASE_BACKUP_SCRIPT"

      exit 1
    fi

    if is_binary_backup_feature_on; then
      log_warn "Warning: Binary backups are configured on the target environment. \nBinary backup is not supported with an external MySQL database. \n\nPlease disable binary backups with 'ghe-config mysql.backup.binary false'"
    fi
  fi
fi

if is_binary_backup_feature_on; then
  # Feature "mysql.backup.binary" is on, which means new backup scripts are available
  if is_binary_backup "$GHE_RESTORE_SNAPSHOT_PATH"; then
    ghe-restore-mysql-binary $GHE_HOSTNAME
  else
    ghe-restore-mysql-logical $GHE_HOSTNAME
  fi
else
  # We do not allow to restore binary backup without "mysql.backup.binary" set
  if is_binary_backup "$GHE_RESTORE_SNAPSHOT_PATH"; then
    log_error "To restore from a binary backup, you have to set ghe-config \"mysql.backup.binary\" to true" >&2
    exit 2
  else
    if is_default_external_database_snapshot; then
      ghe-restore-mysql-logical $GHE_HOSTNAME
    else
      # legacy mode
      ghe-restore-mysql-legacy $GHE_HOSTNAME
    fi
  fi
fi

bm_end "$(basename $0)"
