#!/usr/bin/env bash
# Usage: ghe-restore-external-database-compatibility-check
# GitHub Enterprise checks for external-database related restores.

# Bring in the backup configuration
# shellcheck source=share/github-backup-utils/ghe-backup-config
. "$( dirname "${BASH_SOURCE[0]}" )/ghe-backup-config"

set -e

# Always allow restoring to unconfigured appliances.
# Additional checks are required if the instance is configured.
if is_instance_configured; then

  if internal_database_snapshot_to_external_database; then

    # Restoring settings in this scenario would change BYODB state, which is not supported via backup-utils.
    if $RESTORE_SETTINGS; then
      echo "Restoring the settings of a snapshot from an appliance using the bundled MySQL service to an appliance using an externally-managed MySQL service is not supported."
      echo "Please reconfigure the appliance first, then run ghe-restore again."
      exit 1
    fi

    # Restoring interal DB snapshot to BYODB appliance without passing in --skip-mysql is not supported.
    if ! $SKIP_MYSQL; then
      echo "Restoring a snapshot from an appliance using the bundled MySQL service to an appliance using an externally-managed MySQL service is not supported."
      echo "Please migrate the MySQL data beforehand, then run ghe-restore again, passing in the --skip-mysql flag."
      exit 1
    fi
  fi

  if external_database_snapshot_to_internal_database; then

    # Restoring settings in this scenario would change BYODB state, which is not supported via backup-utils.
    if $RESTORE_SETTINGS; then
      echo "Restoring the settings of a snapshot from an appliance using an externally-managed MySQL service to an appliance using the bundled MySQL service is not supported."
      echo "Please reconfigure the appliance first, then run ghe-restore again."
      exit 1
    fi

    # Restoring BYODB snapshot to internal DB appliance without passing in --skip-mysql is not supported.
    if ! $SKIP_MYSQL; then
      echo "Restoring a snapshot from an appliance using an externally-managed MySQL service to an appliance using the bundled MySQL service is not supported."
      echo "Please migrate the MySQL data beforehand, then run ghe-restore again, passing in the --skip-mysql flag."
      exit 1
    fi
  fi
fi
