#!/usr/bin/env bash

set -euo pipefail

SCRIPT_DIR="$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd)"
# shellcheck source=tools/migration/import_into/lib.sh
source "${SCRIPT_DIR}/lib.sh"

usage() {
  cat <<'USAGE'
Usage:
  OLD_DB_HOST="old-host" OLD_DB_PORT="3306" OLD_DB_USER="user" OLD_DB_PASSWORD="pass" OLD_DB_NAME="old_db" \
  NEW_DB_HOST="new-host" NEW_DB_PORT="3306" NEW_DB_USER="user" NEW_DB_PASSWORD="pass" NEW_DB_NAME="new_db" \
  CLUSTER_IDS="1001,1002" \
  SNAPSHOT_DIR="./snapshot" DRY_RUN="true" \
  ./tools/migration/import_into/migrate_data.sh

Required environment variables:
  OLD_DB_HOST, OLD_DB_PORT, OLD_DB_USER, OLD_DB_PASSWORD, OLD_DB_NAME
  NEW_DB_HOST, NEW_DB_PORT, NEW_DB_USER, NEW_DB_PASSWORD, NEW_DB_NAME
                    MySQL connection fields for old/new metadb
  SNAPSHOT_DIR     Directory to store dump + generated SQL/results

Optional:
  CLUSTER_IDS      Comma-separated cluster IDs. If unset, migrate all rows
                   in import_into_tasks/import_into_precheck_tasks.
  DRY_RUN          true/false. If true, stop after dump generation.
USAGE
}

if [[ "${1:-}" == "-h" || "${1:-}" == "--help" ]]; then
  usage
  exit 0
fi

required_envs=(
  OLD_DB_HOST OLD_DB_PORT OLD_DB_USER OLD_DB_PASSWORD OLD_DB_NAME
  NEW_DB_HOST NEW_DB_PORT NEW_DB_USER NEW_DB_PASSWORD NEW_DB_NAME
  SNAPSHOT_DIR
)

for name in "${required_envs[@]}"; do
  if [[ -z "${!name:-}" ]]; then
    usage
    die "missing required environment variable: ${name}"
  fi
done

cluster_filter="$(build_cluster_filter "${CLUSTER_IDS:-}")"
scope_desc="all rows"
if [[ -n "${CLUSTER_IDS:-}" ]]; then
  scope_desc="cluster ids: ${CLUSTER_IDS//[[:space:]]/}"
fi

timestamp="$(date -u +%Y%m%dT%H%M%SZ)"
run_dir="$(prepare_output_dir "${SNAPSHOT_DIR}" "migration_${timestamp}")"
dump_file="${run_dir}/import_into_data.sql"
dry_run="${DRY_RUN:-false}"

echo "dry_run: ${dry_run}, run_dir: ${run_dir}"

echo "[1/2] Exporting import_into rows from old metadb..."
echo "scope: ${scope_desc}"
run_mysqldump_old \
  --single-transaction \
  --set-gtid-purged=OFF \
  --skip-triggers \
  --no-create-info \
  --insert-ignore \
  --complete-insert \
  --where="${cluster_filter}" \
  --tables "${OLD_DB_NAME}" import_into_tasks import_into_precheck_tasks \
  > "${dump_file}"

case "${dry_run,,}" in
  1|true|yes|on)
    echo "Dry run enabled; skip importing dump into new metadb."
    echo "  run dir: ${run_dir}"
    echo "  dump SQL: ${dump_file}"
    exit 0
    ;;
esac

echo "[2/2] Importing dump into new metadb (no target cleanup)..."
run_mysql_new < ${dump_file}

echo "Migration finished."
echo "  run dir: ${run_dir}"
echo "  dump SQL: ${dump_file}"
