#!/usr/bin/env bash
#/ Usage: ghe-backup-mysql <host>
#/ Backup MySQL from a GitHub instance.
#/
#/ Note: This script typically isn't called directly. It's invoked by the
#/ ghe-backup command.
set -e

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

bm_start "$(basename $0)"

# Perform a host-check and establish the remote version in GHE_REMOTE_VERSION.
ghe_remote_version_required "$GHE_HOSTNAME"

if is_external_database_target; then
  if [ -n "$EXTERNAL_DATABASE_BACKUP_SCRIPT" ]; then
    log_info "Backing up external MySQL database using customer-provided script..."
    $EXTERNAL_DATABASE_BACKUP_SCRIPT
    bm_end "$(basename $0)"
    exit 0
  else
    if is_binary_backup_feature_on; then
      log_warn "Binary backups are configured on the target environment."
      log_warn "Binary backup is not supported with an external MySQL database. Backing up using logical backup strategy. Please disable binary backups with 'ghe-config mysql.backup.binary false', or provide a custom backup script using EXTERNAL_DATABASE_BACKUP_SCRIPT"
    fi

    ghe-backup-mysql-logical
  fi
else
  if is_binary_backup_feature_on; then
    ghe-backup-mysql-binary
  else
    # if incremental backups are turned on, we can't do them with
    # logical backups, so we need to tell the user and exit
    is_inc=$(is_incremental_backup_feature_on)
    if [ $is_inc = true ]; then
      log_warn "Incremental backups are configured on the target environment."
      log_warn "Incremental backup is not supported with a logical MySQL backup. Please disable incremental backups with 'ghe-config mysql.backup.incremental false'"
      exit 1
    fi
    ghe-backup-mysql-logical
  fi
fi

bm_end "$(basename $0)"
