#!/usr/bin/bash
set -euo pipefail

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
AUTOMATION_DIR="$(cd "$SCRIPT_DIR/.." && pwd)"
ENV_FILE="${ENV_FILE:-$AUTOMATION_DIR/.env}"

if [[ ! -f "$ENV_FILE" ]]; then
  echo "Missing env file: $ENV_FILE" >&2
  echo "Copy automation/.env.example to automation/.env and fill in real values first." >&2
  exit 1
fi

set -a
# shellcheck disable=SC1090
source "$ENV_FILE"
set +a

required_vars=(
  SERENITY_BACKUP_HOST
  SERENITY_BACKUP_ROOT
  PD_APPDATA_ROOT
  PD_DATABASES_ROOT
  PD_TANK_DOCKER_ROOT
  PD_DB_DUMP_ROOT
  POSTGRES_CONTAINER
)

for var in "${required_vars[@]}"; do
  if [[ -z "${!var:-}" ]]; then
    echo "Required variable $var is empty in $ENV_FILE" >&2
    exit 1
  fi
done

mkdir -p "$PD_DB_DUMP_ROOT"

DOCKER_BIN="${DOCKER_BIN:-/usr/bin/docker}"
SUDO_BIN="${SUDO_BIN:-/usr/bin/sudo}"
USE_SUDO_FOR_DOCKER="${USE_SUDO_FOR_DOCKER:-true}"
BACKUP_KNOWN_HOSTS="${BACKUP_KNOWN_HOSTS:-${HOME:-/root}/.ssh/known_hosts}"

if [[ ! -x "$DOCKER_BIN" ]]; then
  echo "Docker binary not executable: $DOCKER_BIN" >&2
  exit 1
fi

docker_cmd() {
  if [[ "${EUID:-$(id -u)}" == "0" ]]; then
    "$DOCKER_BIN" "$@"
  elif [[ "$USE_SUDO_FOR_DOCKER" == "true" ]]; then
    "$SUDO_BIN" -n "$DOCKER_BIN" "$@"
  else
    "$DOCKER_BIN" "$@"
  fi
}

timestamp_utc() {
  date -u +"%Y%m%dT%H%M%SZ"
}

ssh_args() {
  local opts="-o BatchMode=yes -o StrictHostKeyChecking=accept-new -o UserKnownHostsFile=$BACKUP_KNOWN_HOSTS"
  if [[ -n "${BACKUP_SSH_KEY:-}" ]]; then
    printf '%s' "-i $BACKUP_SSH_KEY $opts"
  else
    printf '%s' "$opts"
  fi
}

ssh_cmd() {
  printf 'ssh %s' "$(ssh_args)"
}

latest_dump_for_db() {
  local db="$1"
  find "$PD_DB_DUMP_ROOT" -maxdepth 1 -type f -name "${db}_*.sql.gz" | sort | tail -n 1
}
