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

# ── I-6: DNS & TLS — Cloudflare DNS Setup + Verification ───────────────────
#
# Run this AFTER 'terraform apply' creates the telemetry domain mapping.
# The script prints DNS records to create in Cloudflare, then verifies
# propagation, SSL cert status, and HTTPS endpoints.

# ── Configuration ──
PROJECT_ID="complyform-prod"
REGION="us-central1"
LB_IP="34.102.218.22"

# ── Step 1: Get telemetry CNAME target from Terraform ──
echo ""
echo "Step 1: Fetching telemetry CNAME target from Terraform output..."
cd "$(dirname "$0")/.."  # Navigate to infra/ directory
TELEMETRY_CNAME=$(terraform output -raw telemetry_domain_cname_target 2>/dev/null || echo "")
if [ -z "$TELEMETRY_CNAME" ]; then
    echo "  ERROR: Could not read telemetry_domain_cname_target from Terraform state."
    echo "         Run 'terraform apply' first to create the telemetry domain mapping."
    echo "         Then re-run this script."
    exit 1
fi
echo "  Telemetry CNAME target: ${TELEMETRY_CNAME}"

# ── Step 2: Print DNS records table ──
cat <<RECORDS

═══════════════════════════════════════════════════════════════════════════════════
 CLOUDFLARE DNS RECORDS — Create these in Cloudflare Dashboard → DNS → Records
═══════════════════════════════════════════════════════════════════════════════════

 ┌─────────────────────────────────────────────────────────────────────────────┐
 │ IMPORTANT: Proxy status matters!                                           │
 │ • "DNS only" (gray cloud) = Cloudflare passes traffic through, no proxy   │
 │ • "Proxied" (orange cloud) = Cloudflare terminates TLS, applies WAF       │
 │                                                                            │
 │ GCP-backed services MUST be "DNS only" — GCP manages its own TLS via      │
 │ Google-managed certificates. Double-proxying breaks certificate validation.│
 │                                                                            │
 │ Cloudflare Pages services use "Proxied" — Cloudflare handles TLS.         │
 └─────────────────────────────────────────────────────────────────────────────┘

 # ── GCP-backed services (DNS only / gray cloud) ──────────────────────────

 1. api.complyform.dev
    Type: A
    Value: ${LB_IP}
    Proxy: DNS only (gray cloud)
    Notes: Points to GCP Global HTTPS LB. Google-managed TLS.

 2. dashboard.complyform.dev
    Type: A
    Value: ${LB_IP}
    Proxy: DNS only (gray cloud)
    Notes: Same LB as API. URL map routes /dashboard/* paths.

 3. telemetry.complyform.dev
    Type: CNAME
    Value: ${TELEMETRY_CNAME}
    Proxy: DNS only (gray cloud)
    Notes: Cloud Run domain mapping. Google-managed TLS.

 # ── Cloudflare Pages (Proxied / orange cloud) ────────────────────────────

 4. complyform.dev
    Type: (already configured — Cloudflare Pages custom domain)
    Notes: Landing page. Cloudflare handles TLS. No change needed if
           Cloudflare Pages custom domain is already active.

 5. docs.complyform.dev
    Type: CNAME
    Value: <your-docs-pages-project>.pages.dev
    Proxy: Proxied (orange cloud)
    Notes: Starlight docs. Cloudflare Pages custom domain.
           Set up via Cloudflare Pages → Custom domains.

 # ── GitHub Pages ─────────────────────────────────────────────────────────

 6. status.complyform.dev
    Type: CNAME
    Value: complyform.github.io
    Proxy: DNS only (gray cloud)
    Notes: Upptime status page. GitHub handles TLS.

 # ── Email DNS (Postmark) ─────────────────────────────────────────────────
 # Values below are PLACEHOLDERS. Replace with actual values from Postmark
 # dashboard after domain verification (Pre-Phase task #7).

 7. complyform.dev (SPF)
    Type: TXT
    Value: v=spf1 include:spf.mtasv.net ~all
    Notes: Postmark SPF. Add to existing TXT records (don't replace).

 8. <selector>._domainkey.complyform.dev (DKIM)
    Type: CNAME
    Value: <postmark-provided-dkim-value>
    Notes: Postmark DKIM. Selector and value from Postmark dashboard.

 9. _dmarc.complyform.dev
    Type: TXT
    Value: v=DMARC1; p=reject; rua=mailto:dmarc@complyform.dev
    Notes: DMARC reject policy. Strict from day one — all complyform.dev
           email is controlled (Postmark transactional + Google Workspace).

10. pm-bounces.complyform.dev
    Type: CNAME
    Value: <postmark-provided-bounce-domain>
    Notes: Postmark Return-Path for bounce handling.

 # ── Google Workspace (if not already configured) ─────────────────────────

11. complyform.dev (Google Workspace MX)
    Type: MX
    Value: (Google Workspace MX records — likely already configured from
            Pre-Phase task #2)
    Notes: Skip if Google Workspace email is already working.

═══════════════════════════════════════════════════════════════════════════════════

RECORDS

# ── Step 3: Wait for user to create DNS records ──
echo ""
echo "Create the DNS records above in Cloudflare Dashboard, then press Enter..."
read -r

# ── Step 4: DNS propagation check ──
echo ""
echo "Step 4: Checking DNS propagation..."

check_dns() {
    local domain="$1"
    local expected_type="$2"
    local expected_value="$3"

    echo -n "  ${domain} (${expected_type}): "
    local result
    if [ "$expected_type" = "A" ]; then
        result=$(dig +short A "$domain" @1.1.1.1 2>/dev/null | head -1)
    else
        result=$(dig +short CNAME "$domain" @1.1.1.1 2>/dev/null | head -1)
    fi

    if [ -z "$result" ]; then
        echo "WAITING (no record yet)"
        return 1
    elif [ "$expected_type" = "A" ] && [ "$result" = "$expected_value" ]; then
        echo "OK → ${result}"
        return 0
    elif [ "$expected_type" = "CNAME" ]; then
        echo "OK → ${result}"
        return 0
    else
        echo "MISMATCH (got ${result}, expected ${expected_value})"
        return 1
    fi
}

MAX_RETRIES=30
RETRY_INTERVAL=10
for i in $(seq 1 $MAX_RETRIES); do
    echo ""
    echo "DNS check attempt ${i}/${MAX_RETRIES}..."
    ALL_OK=true

    check_dns "api.complyform.dev" "A" "$LB_IP" || ALL_OK=false
    check_dns "dashboard.complyform.dev" "A" "$LB_IP" || ALL_OK=false
    check_dns "telemetry.complyform.dev" "CNAME" "" || ALL_OK=false
    check_dns "status.complyform.dev" "CNAME" "" || ALL_OK=false

    if [ "$ALL_OK" = true ]; then
        echo ""
        echo "All DNS records propagated."
        break
    fi

    if [ "$i" -eq "$MAX_RETRIES" ]; then
        echo ""
        echo "WARNING: Some DNS records have not propagated after $((MAX_RETRIES * RETRY_INTERVAL))s."
        echo "         This is normal — Cloudflare usually propagates in <60s, but can take up to 5min."
        echo "         Re-run this script later to verify."
    else
        echo "  Waiting ${RETRY_INTERVAL}s before next check..."
        sleep "$RETRY_INTERVAL"
    fi
done

# ── Step 5: Google-managed SSL certificate check ──
echo ""
echo "Step 5: Checking Google-managed SSL certificate status..."
CERT_STATUS=$(gcloud compute ssl-certificates describe complyform-api-cert \
    --global --project="$PROJECT_ID" \
    --format="value(managed.status)" 2>/dev/null || echo "UNKNOWN")
echo "  Certificate status: ${CERT_STATUS}"

if [ "$CERT_STATUS" != "ACTIVE" ]; then
    echo ""
    echo "  Certificate is still provisioning. This can take 15-60 minutes after DNS records"
    echo "  are created. Google must verify domain ownership via DNS before issuing the cert."
    echo ""
    echo "  Check status with:"
    echo "    gcloud compute ssl-certificates describe complyform-api-cert --global --project=${PROJECT_ID}"
    echo ""
    echo "  Domain status per-domain:"
    gcloud compute ssl-certificates describe complyform-api-cert \
        --global --project="$PROJECT_ID" \
        --format="yaml(managed.domainStatus)" 2>/dev/null || true
fi

# ── Step 6: HTTPS endpoint verification ──
echo ""
echo "Step 6: Verifying HTTPS endpoints..."

if [ "$CERT_STATUS" = "ACTIVE" ]; then
    echo ""
    echo -n "  https://api.complyform.dev/health → "
    HTTP_CODE=$(curl -s -o /dev/null -w "%{http_code}" --max-time 10 "https://api.complyform.dev/health" 2>/dev/null || echo "FAIL")
    echo "$HTTP_CODE"

    echo -n "  https://dashboard.complyform.dev → "
    HTTP_CODE=$(curl -s -o /dev/null -w "%{http_code}" --max-time 10 "https://dashboard.complyform.dev" 2>/dev/null || echo "FAIL")
    echo "$HTTP_CODE (503 expected — placeholder)"

    echo -n "  https://telemetry.complyform.dev → "
    HTTP_CODE=$(curl -s -o /dev/null -w "%{http_code}" --max-time 10 "https://telemetry.complyform.dev" 2>/dev/null || echo "FAIL")
    echo "$HTTP_CODE (405 expected — POST only)"
else
    echo "  Skipped — SSL cert not yet ACTIVE. Re-run this script after cert provisions."
fi

# ── Step 7: Cloud Run domain mapping verification ──
echo ""
echo "Step 7: Verifying Cloud Run domain mapping for telemetry..."
gcloud run domain-mappings describe \
    --domain="telemetry.complyform.dev" \
    --region="$REGION" \
    --project="$PROJECT_ID" \
    --format="table(metadata.name, status.conditions[0].type, status.conditions[0].status)" \
    2>/dev/null || echo "  WARNING: Domain mapping not found. Run 'terraform apply' first."

# ── Summary ──
echo ""
echo "═══════════════════════════════════════════════════════════════"
echo " I-6 DNS & TLS — Status Summary"
echo "═══════════════════════════════════════════════════════════════"
echo "  DNS:  Check dig output above"
echo "  TLS:  ${CERT_STATUS}"
echo "  Next: If cert is ACTIVE, run HTTPS verification (Step 6)"
echo "        If cert is PROVISIONING, wait 15-60min and re-run"
echo "═══════════════════════════════════════════════════════════════"
