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

SCRIPT_DIR="$(cd -- "$(dirname -- "${BASH_SOURCE[0]}")" && pwd)"
CONFIG_DIR="$SCRIPT_DIR/flyway"

usage() {
  cat <<USAGE
Usage: $(basename "$0") <migrate|validate|repair> --profile <api-test|dev|staging|prod>

Examples:
  ./flyway.sh validate --profile dev
  ./flyway.sh migrate --profile api-test
USAGE
  exit 1
}

if [[ $# -lt 2 ]]; then
  usage
fi

action="$1"
shift
case "$action" in
  migrate|validate|repair) ;;
  *) echo "[ERROR] Unsupported action: $action" >&2; usage ;;
esac

profile=""
while [[ $# -gt 0 ]]; do
  case "$1" in
    --profile|-p)
      [[ $# -ge 2 ]] || usage
      profile="$2"
      shift 2
      ;;
    *)
      echo "[ERROR] Unknown argument: $1" >&2
      usage
      ;;
  esac
done

if [[ -z "$profile" ]]; then
  usage
fi

case "$profile" in
  api-test|apitest)
    profile="api-test"
    config_file="$CONFIG_DIR/api-test.conf"
    ;;
  dev)
    config_file="$CONFIG_DIR/dev.conf"
    ;;
  staging)
    config_file="$CONFIG_DIR/staging.conf"
    ;;
  prod)
    config_file="$CONFIG_DIR/prod.conf"
    ;;
  *)
    echo "[ERROR] Unknown profile: $profile" >&2
    usage
    ;;
esac

if [[ ! -f "$config_file" ]]; then
  echo "[ERROR] Config file not found: $config_file" >&2
  exit 1
fi

confirm_backup() {
  local prompt="$1"
  read -r -p "$prompt (yes/no): " reply
  if [[ "$reply" != "yes" ]]; then
    echo "操作已取消"
    exit 1
  fi
}

if [[ "$profile" == "prod" && ( "$action" == "migrate" || "$action" == "repair" ) ]]; then
  confirm_backup "你备份数据库了吗？"
  confirm_backup "你真的备份了吗？"
fi

exec mvn \
  -f "$SCRIPT_DIR/pom.xml" \
  -pl play-admin \
  -DskipTests \
  "flyway:$action" \
  "-Dflyway.configFiles=$config_file"
