#!/usr/local/bin/bash
#/ Usage: ghe-backup-mysql-logical <host>
#/ Backup MySQL from a GitHub instance using logical backup strategy.
#/
#/ 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)"
log_info "Backing up MySQL database using logical backup strategy ..."

cleanup() {
  hard_limit=$(ulimit -Hf)
  # MySQL backups produce bigger single files, prone to file size limits.
  # This does not show on ssh streaming, only in broken pipe messages. So warn again here.
  if [ "$hard_limit" != "unlimited" ]; then
    log_warn_verbose "Hard limit for file size is set to $hard_limit blocks. Please ensure the limit is set higher than the mysql backup file."
  fi
}

trap_full_cleanup

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

echo "set -o pipefail; ghe-export-mysql | pigz" |
  ghe-ssh "$GHE_HOSTNAME" -- /bin/bash >"$GHE_SNAPSHOT_DIR/mysql.sql.gz"

if is_external_database_target; then
  echo "LOGICAL_EXTERNAL_BACKUP" >"$GHE_SNAPSHOT_DIR/logical-external-database-backup-sentinel"
fi

bm_end "$(basename $0)"
