#!/usr/bin/env bash
#
# Guided customer install / upgrade wrapper for the Nquiry Terraform stack.
#
# Runs the standard sequence from a customer environment directory:
#   terraform init  →  terraform plan -out=plan.out  →  y/N prompt  →  terraform apply plan.out
#
# Usage:
#   cd infrastructure/terraform/environments/<your-env>
#   ../../apply.sh
#
# Or from anywhere with a path:
#   /path/to/infrastructure/terraform/apply.sh /path/to/your/env-dir
#
# See infrastructure/terraform/README.md §5 for prerequisites (state backend,
# Route53 zone, ACM cert, etc.) and the full variable reference.

set -euo pipefail

bold=$'\033[1m'
red=$'\033[31m'
dim=$'\033[2m'
reset=$'\033[0m'

target_dir="${1:-$PWD}"
plan_file="plan.out"

abort() {
  echo
  echo "${red}Aborted.${reset} No changes applied."
  exit 130
}
trap abort INT

cleanup() {
  rm -f "$target_dir/$plan_file"
}
trap cleanup EXIT

if ! command -v terraform >/dev/null 2>&1; then
  echo "${red}terraform not found on PATH.${reset} Install Terraform >= 1.0 and retry." >&2
  exit 1
fi

if [[ ! -d "$target_dir" ]]; then
  echo "${red}Not a directory:${reset} $target_dir" >&2
  exit 1
fi

if [[ ! -f "$target_dir/main.tf" ]]; then
  echo "${red}No main.tf in $target_dir.${reset} Run this from a Terraform environment directory (or pass one as an argument)." >&2
  exit 1
fi

if [[ ! -f "$target_dir/terraform.tfvars" ]]; then
  echo "${red}No terraform.tfvars in $target_dir.${reset} Copy examples/customer-greenfield.tfvars to terraform.tfvars and fill in your values first." >&2
  exit 1
fi

cd "$target_dir"

echo "${bold}==> Initializing Terraform${reset} ${dim}($PWD)${reset}"
terraform init -input=false

echo
echo "${bold}==> Planning${reset}"
terraform plan -input=false -out="$plan_file"

echo
echo "${bold}Review the plan above.${reset} First-time apply creates ~150 resources and takes 15-25 minutes."
read -r -p "Apply this plan? [y/N] " answer
case "$answer" in
  y|Y|yes|YES) ;;
  *) echo "${red}Declined.${reset} Plan discarded."; exit 0 ;;
esac

echo
echo "${bold}==> Applying${reset}"
terraform apply -input=false "$plan_file"

echo
echo "${bold}Apply complete.${reset} Run ${dim}terraform output -json onboarding_summary > onboarding.json${reset} and share with JE Vectors support."
