#!/usr/bin/env bash
# Create a source-controlled, data-free DDL snapshot for the V3 schemas.
set -euo pipefail

usage() {
  echo "Usage: $0 [--output path] [--source-host SSH_ALIAS]" >&2
  exit 2
}

output=""
source_host=""
while (($#)); do
  case "$1" in
    --output)
      (($# >= 2)) || usage
      output="$2"
      shift 2
      ;;
    --source-host)
      (($# >= 2)) || usage
      source_host="$2"
      shift 2
      ;;
    *) usage ;;
  esac
done

[[ -z "$source_host" || "$source_host" =~ ^[A-Za-z0-9][A-Za-z0-9._-]*$ ]] || {
  echo "--source-host must be an SSH alias or host name." >&2
  exit 2
}

repo_root="$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")/../.." && pwd)"

if [[ -z "$output" ]]; then
  output="$repo_root/docs/collectors/SCHEMA-SNAPSHOT-$(date +%F).sql"
fi

mkdir -p "$(dirname "$output")"
tmp="$(mktemp "${output}.tmp.XXXXXX")"
trap 'rm -f "$tmp"' EXIT

dump_args=(
  --databases
  --no-data
  --no-tablespaces
  --skip-comments
  --skip-add-drop-table
  --routines=false
  --events=false
  gwptd_intake gwptd_kernel gwptd_monitoring
)

if [[ -n "$source_host" ]]; then
  # The production client and credentials stay inside the remote DB container.
  # This reads schema only and never copies a secret into the executor shell.
  container="${V3_MYSQL_DOCKER_CONTAINER:-gwptd-v3-prod-mysql}"
  [[ "$container" =~ ^[A-Za-z0-9._-]+$ ]] || {
    echo "V3_MYSQL_DOCKER_CONTAINER contains invalid characters." >&2
    exit 2
  }
  remote_command="docker exec $(printf '%q' "$container") sh -c 'MYSQL_PWD=\"\$MYSQL_ROOT_PASSWORD\" mysqldump --user=root --databases --no-data --no-tablespaces --skip-comments --skip-add-drop-table --routines=false --events=false gwptd_intake gwptd_kernel gwptd_monitoring'"
  ssh -o BatchMode=yes -o ConnectTimeout=10 "$source_host" "$remote_command" >"$tmp"
elif command -v mysqldump >/dev/null && [[ -n "${V3_MYSQL_HOST:-}" && -n "${V3_MYSQL_USER:-}" && -n "${V3_MYSQL_PASSWORD:-}" ]]; then
  MYSQL_PWD="$V3_MYSQL_PASSWORD" mysqldump \
    --host="$V3_MYSQL_HOST" \
    --port="${V3_MYSQL_PORT:-3306}" \
    --user="$V3_MYSQL_USER" \
    "${dump_args[@]}" >"$tmp"
elif command -v docker >/dev/null && docker inspect "${V3_MYSQL_DOCKER_CONTAINER:-gwptd-v3-mysql}" >/dev/null 2>&1; then
  # On s3 the live V3 MySQL client and root password are intentionally kept
  # inside the DB container. Neither is copied into the host shell or output.
  docker exec "${V3_MYSQL_DOCKER_CONTAINER:-gwptd-v3-mysql}" sh -c \
    'MYSQL_PWD="$MYSQL_ROOT_PASSWORD" mysqldump --user=root "$@"' \
    sh "${dump_args[@]}" >"$tmp"
else
  echo "Need mysqldump with V3_MYSQL_HOST/USER/PASSWORD, or a running ${V3_MYSQL_DOCKER_CONTAINER:-gwptd-v3-mysql} container." >&2
  exit 1
fi

# Table AUTO_INCREMENT values reveal approximate row volume and change after
# normal writes even when the DDL contract did not. Keep the schema snapshot
# data-free and deterministic by removing only the table-option counter.
perl -pi -e 's/[ \t]+AUTO_INCREMENT=[0-9]+\b//g; s/[ \t]+$//' "$tmp"
perl -0777 -pi -e 's/\n+\z/\n/' "$tmp"
mv "$tmp" "$output"
trap - EXIT

printf 'Wrote %s (%s tables, %s views)\n' \
  "$output" \
  "$(grep -c '^CREATE TABLE' "$output")" \
  "$(grep -c 'CREATE VIEW' "$output" || true)"
