#!/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]

Deploys the CloudWatch Synthetics demo with Terraform (terraform/). It creates
the same resources, with the same names, as the CloudFormation template: four
canaries (the multi-checks multi_step_http_check, the Puppeteer recorder
user_journey, the Alpha Vantage API canary alpha_vantage_daily, and the visual
monitoring canary visual-monitor), their artifact buckets, the IAM role, the
SNS topic, twelve alarms, the
cloudwatch_rtaa_ninja group, three EventBridge rules with their CloudWatch Logs
groups, and the CloudWatch Logs resource policy.

Delete the CloudFormation stack first. The CloudFormation and Terraform
deployments use identical resource names and cannot coexist. This script checks
(read-only) that the CloudFormation stack does not exist in the primary Region
and stops if it does.

user_journey is a multi-location canary: the primary location is --region
(default us-east-1) and the replica locations are set with --replica-regions
(default ap-south-1,eu-central-1). Terraform manages it through a small
CloudFormation stack named <name-prefix>-user-journey, because the Terraform
providers cannot express canary replicas yet. Because AWS does not allow
multi-location canaries in a Synthetics group, the cloudwatch_rtaa_ninja group
contains multi_step_http_check only.

The three EventBridge rules (default event bus) monitor multi_step_http_check
and user_journey and deliver matched events to the log groups
Synthetic_CloudWatch_Artifact_Error, _Update and _TestRun_Failure (14-day
retention by default; override with --event-log-retention).

visual-monitor compares each run's screenshots with a baseline run, with
ignore regions (IgnoreCoordinates) masking the animated GIF and a 1% variance
threshold. Synthetics keeps the ignore regions only when the baseline is a
concrete run id, so this script passes visual-monitor's current baseline run
id as visual_base_canary_run_id. On the first create it applies with
"nextrun", waits (up to 10 minutes) for the first run to become the baseline,
and applies again with that run id (only the visual canary changes).

Options:
  --endpoint-url <url>         Full HTTPS URL the multi-checks canary checks
                               (default: https://cloudwatch.rtaa.ninja/)
  --notification-email <addr>  Email subscribed to the SNS alarm topic
                               (default: rtaa@amazon.com)
  --api-key <key>              Alpha Vantage API key for alpha_vantage_daily.
                               Required unless TF_VAR_api_key is set, api_key is
                               in terraform/terraform.tfvars, or you are prompted
                               on a terminal. Note: a value given here is visible
                               in the process list; prefer TF_VAR_api_key.
  --api-hostname <host>        Hostname the API canary calls
                               (default: www.alphavantage.co)
  --api-function <function>    Alpha Vantage function query-param value
                               (default: TIME_SERIES_DAILY)
  --stock-symbol <symbol>      Stock ticker the API canary requests (default: AMZN)
  --event-log-retention <days> Retention (days) for the EventBridge monitoring
                               CloudWatch Logs groups (default: 14)
  --name-prefix <prefix>       Prefix for bucket, role, topic and wrapper-stack
                               names (default: cloudwatch-synthetics-demo;
                               lowercase, at most 30 characters)
  --region <region>            AWS Region for every resource and PRIMARY
                               location of user_journey (default: us-east-1)
  --primary-region <region>    Alias for --region
  --replica-regions <list>     Replica locations for user_journey, comma- or
                               space-separated, at most 2 (default:
                               ap-south-1,eu-central-1; "" = single location).
                               Must differ from the primary region.
  --cfn-stack-name <name>      CloudFormation stack that must NOT exist
                               (default: cloudwatch-synthetics-demo)
  --stack-name <name>          Alias for --cfn-stack-name
  --plan-only                  Run terraform init and plan, then stop.
  --auto-approve               Apply the plan without asking for confirmation.
  -h, --help                   Show this help message and exit.

Flags that are not given leave the Terraform defaults (or terraform.tfvars) in
effect, except --region and --replica-regions, which are always passed (with
their defaults) and therefore override primary_region and replica_regions in
terraform.tfvars. The CloudFormation-stack check uses the same Region. The API key is passed
to Terraform only through the TF_VAR_api_key environment variable, never on the
terraform command line. A value in terraform/terraform.tfvars overrides
TF_VAR_api_key (Terraform precedence). The plan file contains the key, so it is
written to a temporary directory and deleted on exit.

AWS sends one subscription confirmation email to the notification address (the
SNS topic exists in the primary Region only); it must be accepted before alarm
notifications are delivered.

Replicas are provisioned asynchronously by Synthetics. Wait until every replica
shows InSync in the primary-Region console before re-running this script,
because Synthetics rejects changes to a multi-location canary while replication
is in progress.
EOF
}

REGION="us-east-1"
REPLICA_REGIONS="ap-south-1,eu-central-1"
CFN_STACK_NAME="cloudwatch-synthetics-demo"
ENDPOINT_URL=""
NOTIFICATION_EMAIL=""
API_KEY=""
API_HOSTNAME=""
API_FUNCTION=""
STOCK_SYMBOL=""
EVENT_LOG_RETENTION=""
NAME_PREFIX=""
PLAN_ONLY="false"
AUTO_APPROVE="false"

while [[ $# -gt 0 ]]; do
  case "$1" in
    --endpoint-url)
      ENDPOINT_URL="$2"
      shift 2
      ;;
    --notification-email)
      NOTIFICATION_EMAIL="$2"
      shift 2
      ;;
    --api-key)
      API_KEY="$2"
      shift 2
      ;;
    --api-hostname)
      API_HOSTNAME="$2"
      shift 2
      ;;
    --api-function)
      API_FUNCTION="$2"
      shift 2
      ;;
    --stock-symbol)
      STOCK_SYMBOL="$2"
      shift 2
      ;;
    --event-log-retention)
      EVENT_LOG_RETENTION="$2"
      shift 2
      ;;
    --name-prefix)
      NAME_PREFIX="$2"
      shift 2
      ;;
    --region|--primary-region)
      REGION="$2"
      shift 2
      ;;
    --replica-regions)
      REPLICA_REGIONS="$2"
      shift 2
      ;;
    --cfn-stack-name|--stack-name)
      CFN_STACK_NAME="$2"
      shift 2
      ;;
    --plan-only)
      PLAN_ONLY="true"
      shift
      ;;
    --auto-approve)
      AUTO_APPROVE="true"
      shift
      ;;
    -h|--help)
      usage
      exit 0
      ;;
    *)
      echo "Unknown argument: $1" >&2
      usage >&2
      exit 1
      ;;
  esac
done

# Prerequisite checks (before any AWS API call)
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

if [[ -n "$ENDPOINT_URL" && ! "$ENDPOINT_URL" =~ ^https:// ]]; then
  echo "Error: --endpoint-url must start with https://" >&2
  exit 1
fi

if [[ ! "$REGION" =~ ^[a-z]{2}(-[a-z]+)+-[0-9]+$ ]]; then
  echo "Error: invalid region '$REGION' in --region." >&2
  exit 1
fi

# Validate the replica locations of the multi-location user_journey canary
# (same rules as deploy.sh). Accepts comma- and/or space-separated values; an
# empty value means a single-location canary.
REPLICA_REGION_1=""
REPLICA_REGION_2=""
REPLICA_COUNT=0
while IFS= read -r replica; do
  [[ -z "$replica" ]] && continue
  if [[ ! "$replica" =~ ^[a-z]{2}(-[a-z]+)+-[0-9]+$ ]]; then
    echo "Error: invalid replica region '$replica' in --replica-regions." >&2
    exit 1
  fi
  if [[ "$replica" == "$REGION" ]]; then
    echo "Error: replica region '$replica' is the primary region; replicas must differ from --region." >&2
    exit 1
  fi
  if [[ "$replica" == "$REPLICA_REGION_1" || "$replica" == "$REPLICA_REGION_2" ]]; then
    echo "Error: duplicate replica region '$replica' in --replica-regions." >&2
    exit 1
  fi
  REPLICA_COUNT=$((REPLICA_COUNT + 1))
  case "$REPLICA_COUNT" in
    1) REPLICA_REGION_1="$replica" ;;
    2) REPLICA_REGION_2="$replica" ;;
    *)
      echo "Error: at most 2 replica regions are supported." >&2
      exit 1
      ;;
  esac
done < <(printf '%s\n' "$REPLICA_REGIONS" | tr ', ' '\n')

if [[ -n "$EVENT_LOG_RETENTION" && ! "$EVENT_LOG_RETENTION" =~ ^[0-9]+$ ]]; then
  echo "Error: --event-log-retention must be a whole number of days." >&2
  exit 1
fi

if [[ -n "$NAME_PREFIX" && ! "$NAME_PREFIX" =~ ^[a-z0-9]([a-z0-9-]{0,28}[a-z0-9])?$ ]]; then
  echo "Error: --name-prefix must be 1-30 lowercase letters, digits or hyphens, starting and ending with a letter or digit." >&2
  exit 1
fi

# Resolve the API key. It is only ever exported as TF_VAR_api_key.
if [[ -n "$API_KEY" ]]; then
  export TF_VAR_api_key="$API_KEY"
elif [[ -n "${TF_VAR_api_key:-}" ]]; then
  :
elif [[ -f "$TF_DIR/terraform.tfvars" ]] && grep -Eq '^[[:space:]]*api_key[[:space:]]*=' "$TF_DIR/terraform.tfvars"; then
  :
elif [[ -t 0 ]]; then
  read -r -s -p "Alpha Vantage API key: " API_KEY
  echo
  if [[ -z "$API_KEY" ]]; then
    echo "Error: no API key entered." >&2
    exit 1
  fi
  export TF_VAR_api_key="$API_KEY"
else
  echo "Error: no API key; set TF_VAR_api_key or pass --api-key" >&2
  exit 1
fi
API_KEY=""

# Read-only identity check.
if ! IDENTITY="$(aws sts get-caller-identity --region "$REGION" --query '[Account, Arn]' --output text 2>/dev/null)"; then
  echo "Error: unable to resolve AWS credentials/identity in region $REGION." >&2
  exit 1
fi
echo "AWS identity: ${IDENTITY}"

# Read-only coexistence check: the CloudFormation stack creates resources with
# the same names and must be deleted before deploying with Terraform.
# describe-stacks by name does not return DELETE_COMPLETE stacks.
if CFN_STATUS="$(aws cloudformation describe-stacks --stack-name "$CFN_STACK_NAME" --region "$REGION" \
    --query 'Stacks[0].StackStatus' --output text 2>&1)"; then
  echo "Error: CloudFormation stack ${CFN_STACK_NAME} exists in ${REGION} (status ${CFN_STATUS})." >&2
  echo "It creates resources with the same names (canaries, alarms, EventBridge rules, log groups," >&2
  echo "Synthetics group, Logs resource policy) and cannot coexist with the Terraform deployment." >&2
  echo "Delete it first:" >&2
  echo "  scripts/teardown.sh --stack-name ${CFN_STACK_NAME} --region ${REGION}" >&2
  exit 1
elif [[ "$CFN_STATUS" != *"does not exist"* ]]; then
  echo "Error: could not determine whether CloudFormation stack ${CFN_STACK_NAME} exists in ${REGION}:" >&2
  echo "  ${CFN_STATUS}" >&2
  exit 1
fi
echo "CloudFormation stack ${CFN_STACK_NAME} does not exist in ${REGION}; continuing."

# Terraform variables. Region and replicas are always passed; other flags only
# when given, so terraform.tfvars and the variable defaults stay in effect.
REPLICA_JSON="["
if [[ -n "$REPLICA_REGION_1" ]]; then
  REPLICA_JSON+="\"${REPLICA_REGION_1}\""
fi
if [[ -n "$REPLICA_REGION_2" ]]; then
  REPLICA_JSON+=",\"${REPLICA_REGION_2}\""
fi
REPLICA_JSON+="]"

VAR_ARGS=(
  -var "primary_region=${REGION}"
  -var "replica_regions=${REPLICA_JSON}"
)
[[ -n "$ENDPOINT_URL" ]] && VAR_ARGS+=(-var "endpoint_url=${ENDPOINT_URL}")
[[ -n "$NOTIFICATION_EMAIL" ]] && VAR_ARGS+=(-var "notification_email=${NOTIFICATION_EMAIL}")
[[ -n "$API_HOSTNAME" ]] && VAR_ARGS+=(-var "api_hostname=${API_HOSTNAME}")
[[ -n "$API_FUNCTION" ]] && VAR_ARGS+=(-var "api_function=${API_FUNCTION}")
[[ -n "$STOCK_SYMBOL" ]] && VAR_ARGS+=(-var "stock_symbol=${STOCK_SYMBOL}")
[[ -n "$EVENT_LOG_RETENTION" ]] && VAR_ARGS+=(-var "event_log_retention_in_days=${EVENT_LOG_RETENTION}")
[[ -n "$NAME_PREFIX" ]] && VAR_ARGS+=(-var "name_prefix=${NAME_PREFIX}")

# visual-monitor baseline: keep the current baseline run id (and with it the
# IgnoreCoordinates). "nextrun" is used only when there is no baseline yet,
# because with nextrun Synthetics rebuilds the screenshot list and drops the
# ignore regions.
UUID_PATTERN='^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$'
VISUAL_CANARY_NAME="$(terraform -chdir="$TF_DIR" output -raw visual_canary_name 2>/dev/null || true)"
[[ "$VISUAL_CANARY_NAME" =~ ^[0-9a-z_-]{1,255}$ ]] || VISUAL_CANARY_NAME="visual-monitor"

current_visual_base_run_id() {
  local run_id
  run_id="$(aws synthetics get-canary --name "$VISUAL_CANARY_NAME" --region "$REGION" \
    --query "Canary.VisualReferences[?BrowserType=='CHROME'] | [0].BaseCanaryRunId" \
    --output text 2>/dev/null || true)"
  if [[ "$run_id" =~ $UUID_PATTERN ]]; then
    printf '%s' "$run_id"
  fi
}

VISUAL_BASE_RUN_ID="$(current_visual_base_run_id)"
VISUAL_BASE_RUN_ID="${VISUAL_BASE_RUN_ID:-nextrun}"
echo "${VISUAL_CANARY_NAME} baseline run: ${VISUAL_BASE_RUN_ID}"

# The saved plan contains the API key in plaintext, so it lives in a temporary
# directory that is removed on exit.
TMP_DIR="$(mktemp -d)"
cleanup() {
  rm -rf "$TMP_DIR"
}
trap cleanup EXIT
PLAN_FILE="$TMP_DIR/deploy.tfplan"

PREFIX_DISPLAY="${NAME_PREFIX:-<default or terraform.tfvars>}"
REPLICA_DISPLAY="${REPLICA_REGION_1}${REPLICA_REGION_2:+ ${REPLICA_REGION_2}}"
echo "Terraform deployment in ${REGION} (primary location); name prefix ${PREFIX_DISPLAY}; user_journey replica locations: ${REPLICA_DISPLAY:-none}"

terraform -chdir="$TF_DIR" init -input=false

if [[ "$PLAN_ONLY" == "true" ]]; then
  terraform -chdir="$TF_DIR" plan -input=false "${VAR_ARGS[@]}" -var "visual_base_canary_run_id=${VISUAL_BASE_RUN_ID}"
  exit $?
fi

terraform -chdir="$TF_DIR" plan -input=false -out="$PLAN_FILE" "${VAR_ARGS[@]}" -var "visual_base_canary_run_id=${VISUAL_BASE_RUN_ID}"

if [[ "$AUTO_APPROVE" != "true" ]]; then
  if [[ ! -t 0 ]]; then
    echo "Error: no terminal to confirm the apply; re-run with --auto-approve." >&2
    exit 1
  fi
  read -r -p "Apply this plan? [y/N] " ANSWER
  case "$ANSWER" in
    y|Y|yes|YES|Yes) ;;
    *)
      echo "Aborted; nothing applied."
      exit 0
      ;;
  esac
fi

# First create: the first run became the baseline without the ignore regions.
# Wait for it, then apply again with its run id so the IgnoreCoordinates apply.
# The plan was already approved, and this second apply only changes the
# visual canary's baseline, so it runs without another prompt.
apply_visual_baseline() {
  [[ "$VISUAL_BASE_RUN_ID" == "nextrun" ]] || return 0
  echo "Waiting for the first ${VISUAL_CANARY_NAME} run to become the baseline..."
  local new_id=""
  for _ in $(seq 1 40); do
    new_id="$(current_visual_base_run_id)"
    [[ -n "$new_id" ]] && break
    sleep 15
  done
  if [[ -z "$new_id" ]]; then
    echo "Warning: ${VISUAL_CANARY_NAME} has no baseline run yet, so its ignore regions are not applied." >&2
    echo "Re-run this script once the canary has completed a run." >&2
    return 0
  fi
  echo "Applying ${VISUAL_CANARY_NAME} baseline run ${new_id} so the ignore regions apply..."
  terraform -chdir="$TF_DIR" apply -input=false -auto-approve "${VAR_ARGS[@]}" -var "visual_base_canary_run_id=${new_id}"
}

if terraform -chdir="$TF_DIR" apply -input=false "$PLAN_FILE" && apply_visual_baseline; then
  echo "Apply succeeded. Terraform outputs:"
  terraform -chdir="$TF_DIR" output
  echo "user_journey replicas are provisioned asynchronously. Check replication status in the"
  echo "${REGION} CloudWatch Synthetics console and wait for InSync before re-running this script."
  echo "Only one SNS subscription confirmation email is sent (primary Region)."
else
  # Wrapper stack name: Terraform output if the state has it, else --name-prefix,
  # else name_prefix from terraform.tfvars, else the default.
  WRAPPER_STACK="$(terraform -chdir="$TF_DIR" output -raw recorder_canary_stack_name 2>/dev/null || true)"
  if [[ -z "$WRAPPER_STACK" ]]; then
    HINT_PREFIX="$NAME_PREFIX"
    if [[ -z "$HINT_PREFIX" && -f "$TF_DIR/terraform.tfvars" ]]; then
      HINT_PREFIX="$(sed -n 's/^[[:space:]]*name_prefix[[:space:]]*=[[:space:]]*"\([^"]*\)".*/\1/p' "$TF_DIR/terraform.tfvars" | head -n 1)"
    fi
    WRAPPER_STACK="${HINT_PREFIX:-cloudwatch-synthetics-demo}-user-journey"
  fi
  echo "Apply failed. Re-running this script is safe (Terraform resumes from its state)." >&2
  echo "For user_journey, inspect the wrapper stack events with:" >&2
  echo "  aws cloudformation describe-stack-events --stack-name ${WRAPPER_STACK} --region ${REGION}" >&2
  exit 1
fi
