#!/usr/bin/env bash
# Destroys an ephemeral ows-coda environment and cleans up its workspace.
#
# Usage:  ./scripts/destroy-ephemeral.sh <instance-name>
# Example: ./scripts/destroy-ephemeral.sh pr-42
set -euo pipefail

NAME="${1:?Usage: $0 <instance-name>}"
DIR="$(cd "$(dirname "$0")/.." && pwd)"

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"
terraform destroy -var="instance=${NAME}"

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

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

echo ""
echo "========================================"
echo "Ephemeral environment destroyed!"
echo "========================================"
echo ""
echo "You may also want to drop the database on the shared RDS cluster:"
echo ""
echo "  DROP DATABASE IF EXISTS \`${DB_NAME}\`;"
echo ""
