#!/usr/bin/env bash
# Destroys an ephemeral ows-coda environment and cleans up its workspace.
#
# Usage:  ./scripts/destroy-ephemeral.sh <instance-name> [options]
# Example: ./scripts/destroy-ephemeral.sh pr-42
# Example: ./scripts/destroy-ephemeral.sh pr-42 --db-host <host> --db-user coda_ephemeral --db-pass <pass>
#
# Options:
#   --db-host HOST   RDS hostname. If provided with --db-user and --db-pass, drops the database automatically.
#   --db-user USER   MySQL user for DROP DATABASE (e.g. coda_ephemeral).
#   --db-pass PASS   MySQL password.
#   --yes, -y        Skip confirmation prompt (for CI/automation).
set -euo pipefail

NAME="${1:?Usage: $0 <instance-name> [--db-host HOST --db-user USER --db-pass PASS]}"
shift
DIR="$(cd "$(dirname "$0")/.." && pwd)"

# Parse optional flags
DB_HOST=""
DB_USER=""
DB_PASS=""
AUTO_APPROVE=false
while [[ $# -gt 0 ]]; do
  case "$1" in
    --db-host) DB_HOST="$2"; shift 2 ;;
    --db-user) DB_USER="$2"; shift 2 ;;
    --db-pass) DB_PASS="$2"; shift 2 ;;
    --yes|-y)  AUTO_APPROVE=true; shift ;;
    *) echo "Unknown option: $1"; exit 1 ;;
  esac
done

DB_NAME="coda_${NAME//-/_}"

echo "==> Destroying ephemeral environment: qa-ows-coda-${NAME}"
cd "$DIR"

terraform init -input=false

# Ensure we return to the default workspace even if destroy fails.
cleanup() { terraform workspace select default 2>/dev/null; }
trap cleanup ERR EXIT

terraform workspace select "$NAME"

if [[ "$AUTO_APPROVE" != true ]]; then
  echo ""
  echo "About to run terraform destroy for ephemeral instance: ${NAME}"
  echo "This will permanently delete all resources for qa-ows-coda-${NAME}."
  read -p "Continue? (y/N): " -n 1 -r
  echo
  if [[ ! $REPLY =~ ^[Yy]$ ]]; then
    echo "Aborted."
    terraform workspace select default 2>/dev/null
    exit 1
  fi
fi

terraform destroy -var="instance=${NAME}" -auto-approve

# cleanup trap handles workspace select; now delete the workspace.
trap - ERR EXIT
terraform workspace select default
terraform workspace delete "$NAME"

# ──────────────────────────────────────────────
# Database cleanup
# ──────────────────────────────────────────────

if [[ -n "$DB_HOST" && -n "$DB_USER" && -n "$DB_PASS" ]]; then
  echo "==> Dropping database: ${DB_NAME}"
  mysql -h "$DB_HOST" -u "$DB_USER" -p"$DB_PASS" --ssl-mode=REQUIRED \
    -e "DROP DATABASE IF EXISTS \`${DB_NAME}\`;" \
    && echo "Database ${DB_NAME} dropped." \
    || echo "WARNING: Failed to drop database ${DB_NAME}. Drop it manually."
else
  echo ""
  echo "You may also want to drop the database on the shared RDS cluster:"
  echo ""
  echo "  DROP DATABASE IF EXISTS \`${DB_NAME}\`;"
fi

echo ""
echo "========================================"
echo "Ephemeral environment destroyed!"
echo "========================================"
