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

# Run only from the private Cloudflare Worker repository that serves api.codecr.org.
# Usage: ./activate-codecr-email-funnel.sh /secure/path/.env.production

ENV_FILE="${1:-.env.production}"
test -r "$ENV_FILE" || { echo "FAIL: unreadable production environment file" >&2; exit 1; }

set -a
# shellcheck disable=SC1090
. "$ENV_FILE"
set +a

fail() { echo "FAIL: $*" >&2; exit 1; }
require() {
  local key="$1"
  local value="${!key:-}"
  test -n "$value" || fail "$key is empty"
  case "$value" in
    __REQUIRED_*|*"[Insert Corporate Headquarters Address Here]"*) fail "$key still contains a placeholder" ;;
  esac
}

for tool in curl dig jq npx; do command -v "$tool" >/dev/null 2>&1 || fail "$tool is required"; done

for key in \
  EMAIL_PROVIDER EMAIL_SYSTEM_STATE EMAIL_SEND_ENABLED DOUBLE_OPT_IN_REQUIRED \
  SUPPRESSION_API_HEALTH_ENDPOINT EMAIL_CONTROL_PLANE_URL \
  CONTROLLER_IDENTITY CONTROLLER_POSTAL_ADDRESS PRIVACY_CONTACT \
  EMAIL_SENDING_DOMAIN EMAIL_PROVIDER_DOMAIN_ID \
  RESEND_MAIL_FROM_HOST RESEND_MAIL_FROM_MX RESEND_SPF_VALUE \
  RESEND_DKIM_HOST RESEND_DKIM_VALUE DMARC_HOST DMARC_VALUE; do
  require "$key"
done

test "$EMAIL_PROVIDER" = "resend" || fail "EMAIL_PROVIDER must be resend"
test "$EMAIL_SENDING_DOMAIN" = "codecr.org" || fail "sending-domain drift"
test "$PRIVACY_CONTACT" = "privacy@codecr.org" || fail "privacy-contact drift"
test "$EMAIL_SYSTEM_STATE" = "fail-closed" || fail "activation must begin fail-closed"
test "$EMAIL_SEND_ENABLED" = "false" || fail "send must be false before verification"
test "$DOUBLE_OPT_IN_REQUIRED" = "true" || fail "double opt-in cannot be disabled"

txt_matches() {
  local host="$1" expected="$2"
  dig +short TXT "$host" | tr -d '"' | grep -Fqx "$expected"
}

mx_matches() {
  local host="$1" expected="${2%.}."
  dig +short MX "$host" | awk '{print $2}' | grep -Fqx "$expected"
}

mx_matches "$RESEND_MAIL_FROM_HOST" "$RESEND_MAIL_FROM_MX" || fail "Resend MAIL FROM MX mismatch"
txt_matches "$RESEND_MAIL_FROM_HOST" "$RESEND_SPF_VALUE" || fail "Resend SPF mismatch"
txt_matches "$RESEND_DKIM_HOST" "$RESEND_DKIM_VALUE" || fail "Resend DKIM mismatch"
txt_matches "$DMARC_HOST" "$DMARC_VALUE" || fail "DMARC record does not match the approved value"

curl --fail --silent --show-error "$SUPPRESSION_API_HEALTH_ENDPOINT" \
  | jq -e '.status == "ready" and .durable == true and .write_before_send == true' >/dev/null \
  || fail "suppression service is not ready and durable"

if test -z "${EMAIL_ACTIVATION_CONTROL_TOKEN:-}"; then
  read -r -s -p "Scoped email activation control token: " EMAIL_ACTIVATION_CONTROL_TOKEN </dev/tty
  printf '\n' >/dev/tty
fi
test "${#EMAIL_ACTIVATION_CONTROL_TOKEN}" -ge 32 || fail "activation control token is missing or implausibly short"
trap 'unset EMAIL_ACTIVATION_CONTROL_TOKEN PREFLIGHT ACTIVATION_RESPONSE' EXIT

# Deploy code with the checked-in production configuration still fail-closed.
# Required secret bindings were injected separately with inject-codecr-resend-secrets.sh.
npx wrangler deploy --env production

PREFLIGHT="$(curl --fail --silent --show-error \
  --header "Authorization: Bearer $EMAIL_ACTIVATION_CONTROL_TOKEN" \
  "$EMAIL_CONTROL_PLANE_URL/v1/email/activation/preflight")"

jq -e '
  .provider == "resend" and
  .provider_domain == "verified" and
  .provider_webhook == "verified" and
  .secret_bindings.RESEND_API_KEY == "present" and
  .secret_bindings.RESEND_WEBHOOK_SECRET == "present" and
  .secret_bindings.SUPPRESSION_API_ENDPOINT == "present" and
  .suppression == "ready" and
  .double_opt_in == "enforced" and
  .controller_record == "complete" and
  .published_notice == "complete" and
  .seed_delivery == "passed"
' <<<"$PREFLIGHT" >/dev/null || fail "control-plane preflight rejected activation"

ACTIVATION_RESPONSE="$(curl --fail --silent --show-error \
  --request POST \
  --header "Authorization: Bearer $EMAIL_ACTIVATION_CONTROL_TOKEN" \
  --header "Content-Type: application/json" \
  --header "Idempotency-Key: email-activation-2026-09-05-v4" \
  --data '{"from":"fail-closed","to":"active","provider":"resend","notice_version":"2026-09-05.v4","double_opt_in_required":true,"persistence_required":"durable"}' \
  "$EMAIL_CONTROL_PLANE_URL/v1/email/activation")"

jq -e '
  .state == "active" and
  .email_send_enabled == true and
  .double_opt_in_required == true and
  .provider == "resend" and
  .persistence == "durable" and
  (.state_revision | type == "number")
' <<<"$ACTIVATION_RESPONSE" >/dev/null || fail "activation response did not prove a durable active state"

echo "PASS: codecr onboarding email state is active; Resend is verified and double opt-in remains mandatory."
