#!/usr/bin/env bash
# Fail-closed teardown verification for both AWS regions and the Azure RG.
# Read-only: this script creates no cloud resources and changes no cloud state.
set -euo pipefail

ROOT="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
TMP_JSON="$(mktemp)"
TMP_MD="$(mktemp)"
trap 'rm -f "$TMP_JSON" "$TMP_MD"' EXIT

"$ROOT/scripts/inventory.sh" "$TMP_JSON" "$TMP_MD"

if ! jq -e '.complete == true and ((.errors // []) | length == 0)' "$TMP_JSON" >/dev/null; then
  echo "ERROR: inventory is unreachable or partial. Teardown cannot be certified." >&2
  jq -r '(.errors // [])[] | "ERROR: \(.provider) / \(.scope) / \(.resource): \(.detail)"' "$TMP_JSON" >&2
  exit 2
fi

remaining="$(jq '
  [
    (.aws.regions[] |
      (.vpcs // [])[],
      (.subnets // [])[],
      (.instances // [])[],
      (.eips // [])[],
      (.securityGroups // [])[],
      (.internetGateways // [])[],
      (.routeTables // [])[],
      (.vpnGateways // [])[],
      (.customerGateways // [])[],
      (.vpnConnections // [])[],
      (.alarms // [])[],
      (.cloudTrails // [])[],
      (.flowLogs // [])[],
      (.stacks // [])[]
    ) | select(
      ((.name // "") | test("eg334s"; "i")) or
      ((.bucket // "") | test("eg334s"; "i"))
    )
  ] | length
  +
  ([.aws.regions[] | (.snsTopics // [])[] | select(test("eg334s"; "i"))] | length)
  +
  ((.aws.buckets // []) | length)
  +
  ((.azure.resources // []) | length)
' "$TMP_JSON")"

if [ "$remaining" -ne 0 ]; then
  echo "FAIL: $remaining project resource(s) remain. Review the inventory below." >&2
  cat "$TMP_MD"
  exit 1
fi

echo "PASS: no EG334S resources were found in us-east-1, eu-west-1 or eg334s-rg."
echo "TBD: the team/lecturer must decide whether the Cloudflare evidence site is retained or decommissioned."

