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

SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
TF_DIR="$SCRIPT_DIR/../terraform"

usage() {
  cat <<EOF
Usage: $(basename "$0") [options]

Destroys the Terraform deployment of the CloudWatch Synthetics demo (terraform/),
including all four canaries. Destroying the user_journey wrapper stack
(<name-prefix>-user-journey) deletes the user_journey canary and its replicas
(ap-south-1 and eu-central-1 by default).

Options:
  --region <region>     Expected primary Region of the deployment. Optional:
                        the Region is read from the Terraform state
                        (primary_region output), and the script stops if
                        --region does not match it.
  --auto-approve        Do not ask for confirmation.
  -h, --help            Show this help message and exit.

The primary_region and replica_regions values recorded in the Terraform state
are passed to every terraform destroy, so the destroy targets the Regions the
deployment was created in (even if it was deployed with a non-default
--region or --replica-regions). If the state cannot be read, the script stops
with an error; only a missing or empty state counts as "nothing to do".

Order of operations:
  1. Destroy the four canaries first (targeted destroy), so no scheduled run
     writes new artifacts. This also removes the resources that depend on them
     (the group association and the twelve alarms).
  2. Empty the four artifact buckets (artifact_bucket_name,
     recorder_artifact_bucket_name, api_artifact_bucket_name,
     visual_artifact_bucket_name outputs).
     Terraform, like CloudFormation, cannot delete a non-empty bucket.
  3. Destroy everything else. If that fails (for example because a last run
     wrote artifacts in the meantime), the buckets are emptied again and the
     destroy is retried once.

The Lambda log groups that Synthetics creates (/aws/lambda/cwsyn-<canary-name>-*)
are not managed by Terraform and remain in each Region, including the replica
Regions; clean those up separately if you no longer need them. The Terraform-
managed canary code bucket and its objects are destroyed. The local state file
remains (empty).
EOF
}

REGION=""
AUTO_APPROVE="false"

while [[ $# -gt 0 ]]; do
  case "$1" in
    --region)
      REGION="$2"
      shift 2
      ;;
    --auto-approve)
      AUTO_APPROVE="true"
      shift
      ;;
    -h|--help)
      usage
      exit 0
      ;;
    *)
      echo "Unknown argument: $1" >&2
      usage >&2
      exit 1
      ;;
  esac
done

if ! command -v terraform >/dev/null 2>&1; then
  echo "Error: Terraform ('terraform') not found on PATH." >&2
  exit 1
fi

if ! command -v aws >/dev/null 2>&1; then
  echo "Error: AWS CLI ('aws') not found on PATH." >&2
  exit 1
fi

terraform -chdir="$TF_DIR" init -input=false >/dev/null

TMP_DIR="$(mktemp -d)"
cleanup() {
  rm -rf "$TMP_DIR"
}
trap cleanup EXIT

# Tell a missing/empty state (nothing to do) apart from a state read error.
STATE_RC=0
STATE_LIST="$(terraform -chdir="$TF_DIR" state list 2>"$TMP_DIR/state.err")" || STATE_RC=$?
if [[ "$STATE_RC" -ne 0 ]]; then
  if grep -q "No state file was found" "$TMP_DIR/state.err"; then
    STATE_LIST=""
  else
    echo "Error: could not read the Terraform state (terraform state list exited ${STATE_RC}):" >&2
    cat "$TMP_DIR/state.err" >&2
    exit 1
  fi
fi
if [[ -z "$STATE_LIST" ]]; then
  echo "No Terraform-managed resources in state. Nothing to do."
  exit 0
fi

tf_output() {
  terraform -chdir="$TF_DIR" output -raw "$1" 2>/dev/null || true
}

# The deployment's Regions come from the state, not from the variable defaults.
STATE_REGION="$(tf_output primary_region)"
if [[ -n "$STATE_REGION" ]]; then
  if [[ -n "$REGION" && "$REGION" != "$STATE_REGION" ]]; then
    echo "Error: --region ${REGION} does not match the deployment's primary Region ${STATE_REGION} (Terraform state)." >&2
    echo "Re-run without --region, or with --region ${STATE_REGION}." >&2
    exit 1
  fi
  REGION="$STATE_REGION"
else
  REGION="${REGION:-us-east-1}"
  echo "Warning: primary_region output not found in the Terraform state; using ${REGION}." >&2
fi

# replica_regions is a comma-separated output; it is absent (null) when the
# canary has no replica locations.
STATE_REPLICAS="$(tf_output replica_regions)"
REPLICA_JSON="["
SEP=""
while IFS= read -r replica; do
  [[ -z "$replica" ]] && continue
  REPLICA_JSON+="${SEP}\"${replica}\""
  SEP=","
done < <(printf '%s\n' "$STATE_REPLICAS" | tr ',' '\n')
REPLICA_JSON+="]"

DESTROY_VARS=(
  -var "primary_region=${REGION}"
  -var "replica_regions=${REPLICA_JSON}"
)
echo "Deployment primary Region ${REGION}; user_journey replica locations: ${STATE_REPLICAS:-none}"

if ! aws sts get-caller-identity --region "$REGION" >/dev/null 2>&1; then
  echo "Error: unable to resolve AWS credentials/identity in region $REGION." >&2
  exit 1
fi

# Destroy evaluates the configuration, which requires the api_key variable.
# The value is not sent anywhere during destroy, so a placeholder is enough
# when none is set. It is never printed.
export TF_VAR_api_key="${TF_VAR_api_key:-unused-during-destroy}"

ARTIFACT_BUCKET="$(tf_output artifact_bucket_name)"
RECORDER_ARTIFACT_BUCKET="$(tf_output recorder_artifact_bucket_name)"
API_ARTIFACT_BUCKET="$(tf_output api_artifact_bucket_name)"
VISUAL_ARTIFACT_BUCKET="$(tf_output visual_artifact_bucket_name)"
WRAPPER_STACK="$(tf_output recorder_canary_stack_name)"
WRAPPER_STACK="${WRAPPER_STACK:-<name-prefix>-user-journey}"

if [[ "$AUTO_APPROVE" != "true" ]]; then
  if [[ ! -t 0 ]]; then
    echo "Error: no terminal to confirm the destroy; re-run with --auto-approve." >&2
    exit 1
  fi
  read -r -p "This destroys all Terraform-managed resources in terraform/ (region ${REGION}). Continue? [y/N] " ANSWER
  case "$ANSWER" in
    y|Y|yes|YES|Yes) ;;
    *)
      echo "Aborted; nothing destroyed."
      exit 0
      ;;
  esac
fi

# Empty an artifact bucket before destroying it (same logic as teardown.sh,
# but the bucket name comes from the Terraform outputs).
empty_bucket() {
  local bucket="$1"

  if [[ -z "$bucket" || "$bucket" == "None" ]]; then
    return 0
  fi

  if ! aws s3api head-bucket --bucket "$bucket" --region "$REGION" >/dev/null 2>&1; then
    return 0
  fi

  echo "Emptying artifact bucket ${bucket}..."
  aws s3 rm "s3://${bucket}" --recursive --region "$REGION" >/dev/null
  # Also remove any object versions/delete markers in case versioning was
  # ever enabled on the bucket, which `s3 rm` alone does not clean up.
  local versions_and_markers
  versions_and_markers="$(aws s3api list-object-versions --bucket "$bucket" --region "$REGION" \
    --query '{Objects: Versions[].{Key:Key,VersionId:VersionId}}' --output json 2>/dev/null || echo '{"Objects": null}')"
  if [[ "$(echo "$versions_and_markers" | grep -c '"Key"')" -gt 0 ]]; then
    aws s3api delete-objects --bucket "$bucket" --region "$REGION" --delete "$versions_and_markers" >/dev/null 2>&1 || true
  fi
  local markers
  markers="$(aws s3api list-object-versions --bucket "$bucket" --region "$REGION" \
    --query '{Objects: DeleteMarkers[].{Key:Key,VersionId:VersionId}}' --output json 2>/dev/null || echo '{"Objects": null}')"
  if [[ "$(echo "$markers" | grep -c '"Key"')" -gt 0 ]]; then
    aws s3api delete-objects --bucket "$bucket" --region "$REGION" --delete "$markers" >/dev/null 2>&1 || true
  fi
}

empty_all_buckets() {
  empty_bucket "$ARTIFACT_BUCKET"
  empty_bucket "$RECORDER_ARTIFACT_BUCKET"
  empty_bucket "$API_ARTIFACT_BUCKET"
  empty_bucket "$VISUAL_ARTIFACT_BUCKET"
}

failure_hints() {
  echo "Terraform destroy did not complete. Next steps:" >&2
  echo "  - Inspect the user_journey wrapper stack events:" >&2
  echo "      aws cloudformation describe-stack-events --stack-name ${WRAPPER_STACK} --region ${REGION}" >&2
  echo "  - If user_journey could not be deleted because it still has replica locations, remove the" >&2
  echo "    replica locations from the canary in the ${REGION} CloudWatch Synthetics console." >&2
  echo "  - Then re-run this script." >&2
}

# 1. Stop the artifact writers: destroy the canaries (and their dependents).
echo "Destroying the four canaries first..."
if ! terraform -chdir="$TF_DIR" destroy -input=false -auto-approve "${DESTROY_VARS[@]}" \
    -target=awscc_synthetics_canary.multi_step_http_check \
    -target=awscc_synthetics_canary.alpha_vantage_daily \
    -target=awscc_synthetics_canary.visual_monitor \
    -target=aws_cloudformation_stack.user_journey; then
  failure_hints
  exit 1
fi

# 2. Empty the artifact buckets.
empty_all_buckets

# 3. Destroy everything else; retry once after re-emptying the buckets.
echo "Destroying the remaining resources..."
if ! terraform -chdir="$TF_DIR" destroy -input=false -auto-approve "${DESTROY_VARS[@]}"; then
  echo "Retrying once after re-emptying the artifact buckets..."
  empty_all_buckets
  if ! terraform -chdir="$TF_DIR" destroy -input=false -auto-approve "${DESTROY_VARS[@]}"; then
    failure_hints
    exit 1
  fi
fi

echo "Terraform deployment destroyed."
echo "Note: the Synthetics Lambda log groups (/aws/lambda/cwsyn-<canary-name>-*) are not managed by"
echo "Terraform and remain in each Region (primary and replica Regions)."
