#!/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_PROVIDER_SECRET_KEY WEBHOOK_SIGNING_SECRET \
  PROVIDER_WEBHOOK_VERIFICATION_KEY EMAIL_ACTIVATION_CONTROL_TOKEN \
  SUPPRESSION_API_ENDPOINT SUPPRESSION_API_HEALTH_ENDPOINT EMAIL_CONTROL_PLANE_URL \
  CONTROLLER_IDENTITY CONTROLLER_POSTAL_ADDRESS PRIVACY_CONTACT \
  EMAIL_SENDING_DOMAIN EMAIL_PROVIDER_DOMAIN_ID DMARC_HOST DMARC_VALUE; do
  require "$key"
done

test "${#EMAIL_PROVIDER_SECRET_KEY}" -ge 24 || fail "EMAIL_PROVIDER_SECRET_KEY is implausibly short"
test "${#WEBHOOK_SIGNING_SECRET}" -ge 32 || fail "WEBHOOK_SIGNING_SECRET must contain at least 32 characters"
test "$SUPPRESSION_API_ENDPOINT" = "https://api.codecr.org/v1/email/suppressions" || fail "suppression endpoint 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"
}

cname_matches() {
  local host="$1" expected="${2%.}."
  test "$(dig +short CNAME "$host" | tail -n 1)" = "$expected"
}

txt_matches "$DMARC_HOST" "$DMARC_VALUE" || fail "DMARC record does not match the approved value"

case "$EMAIL_PROVIDER" in
  resend)
    require RESEND_MAIL_FROM_HOST
    require RESEND_MAIL_FROM_MX
    require RESEND_SPF_VALUE
    require RESEND_DKIM_HOST
    require RESEND_DKIM_VALUE
    test "$(dig +short MX "$RESEND_MAIL_FROM_HOST" | awk 'NR==1 {print $2}')" = "${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"
    ;;
  sendgrid)
    require SENDGRID_RETURN_PATH_HOST
    require SENDGRID_RETURN_PATH_TARGET
    require SENDGRID_DKIM1_HOST
    require SENDGRID_DKIM1_TARGET
    require SENDGRID_DKIM2_HOST
    require SENDGRID_DKIM2_TARGET
    cname_matches "$SENDGRID_RETURN_PATH_HOST" "$SENDGRID_RETURN_PATH_TARGET" || fail "SendGrid return-path CNAME mismatch"
    cname_matches "$SENDGRID_DKIM1_HOST" "$SENDGRID_DKIM1_TARGET" || fail "SendGrid DKIM 1 CNAME mismatch"
    cname_matches "$SENDGRID_DKIM2_HOST" "$SENDGRID_DKIM2_TARGET" || fail "SendGrid DKIM 2 CNAME mismatch"
    ;;
  *) fail "EMAIL_PROVIDER must be resend or sendgrid" ;;
esac

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"

# Store secrets in the production Worker without echoing them.
printf '%s' "$EMAIL_PROVIDER_SECRET_KEY" | npx wrangler secret put EMAIL_PROVIDER_SECRET_KEY --env production >/dev/null
printf '%s' "$WEBHOOK_SIGNING_SECRET" | npx wrangler secret put WEBHOOK_SIGNING_SECRET --env production >/dev/null
printf '%s' "$PROVIDER_WEBHOOK_VERIFICATION_KEY" | npx wrangler secret put PROVIDER_WEBHOOK_VERIFICATION_KEY --env production >/dev/null
printf '%s' "$EMAIL_ACTIVATION_CONTROL_TOKEN" | npx wrangler secret put EMAIL_ACTIVATION_CONTROL_TOKEN --env production >/dev/null

# wrangler production vars must still declare EMAIL_SEND_ENABLED=false for this deploy.
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_domain == "verified" and
  .provider_webhook == "verified" and
  .suppression == "ready" and
  .double_opt_in == "enforced" and
  .controller_record == "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-v3" \
  --data '{"from":"fail-closed","to":"active","notice_version":"2026-09-05.v3","double_opt_in_required":true}' \
  "$EMAIL_CONTROL_PLANE_URL/v1/email/activation")"

jq -e '.state == "active" and .email_send_enabled == true and .double_opt_in_required == true' \
  <<<"$ACTIVATION_RESPONSE" >/dev/null || fail "activation response did not prove active state"

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