#!/usr/bin/env bash
# Fibromuebles ERP DEMO — Cloudflare deploy
# Idempotente: crea DNS CNAMEs + reglas de ingress del túnel para erp-demo / erp-demo-db.
set -euo pipefail

source /home/edd/.cloudflare_secrets

EMAIL="$CLOUDFLARE_EMAIL"
KEY="$CLOUDFLARE_GLOBAL_API_KEY"
ACC="$CLOUDFLARE_ACCOUNT_ID"
TUN="$CLOUDFLARE_TUNNEL_ID"
ZONE="$CLOUDFLARE_ZONE_BAH_IA"
TARGET="${TUN}.cfargotunnel.com"
CFAPI="https://api.cloudflare.com/client/v4"
H=(-H "X-Auth-Email: $EMAIL" -H "X-Auth-Key: $KEY" -H "Content-Type: application/json")

for SUB in erp-demo erp-demo-db; do
  ID=$(curl -s "$CFAPI/zones/$ZONE/dns_records?name=$SUB.bah-ia.com.ar" "${H[@]}" \
    | python3 -c 'import sys,json;d=json.load(sys.stdin);print(d["result"][0]["id"] if d.get("result") else "")')
  if [ -z "$ID" ]; then
    curl -s -X POST "$CFAPI/zones/$ZONE/dns_records" "${H[@]}" \
      -d "{\"type\":\"CNAME\",\"name\":\"$SUB\",\"content\":\"$TARGET\",\"proxied\":true}" \
      | python3 -c 'import sys,json;d=json.load(sys.stdin);print("DNS created" if d["success"] else d["errors"])'
  else
    echo "DNS exists: $SUB.bah-ia.com.ar"
  fi
done

CFG=$(curl -s "$CFAPI/accounts/$ACC/cfd_tunnel/$TUN/configurations" "${H[@]}")
python3 - "$CFG" <<'PY' > /tmp/erp_demo_tunnel.json
import json
import sys

cfg = json.loads(sys.argv[1])
config = cfg["result"]["config"]
ingress = config.get("ingress", [])
want = {
    "erp-demo.bah-ia.com.ar": "http://eddos-web-server:80",
    "erp-demo-db.bah-ia.com.ar": "http://eddos-web-server:80",
}
have = {rule.get("hostname") for rule in ingress}
catch = ingress[-1] if ingress and "hostname" not in ingress[-1] else {"service": "http_status:404"}
body = [rule for rule in ingress if "hostname" in rule]

for host, service in want.items():
    if host not in have:
        body.append({"hostname": host, "service": service})

body.append(catch)
config["ingress"] = body
print(json.dumps({"config": config}))
PY

curl -s -X PUT "$CFAPI/accounts/$ACC/cfd_tunnel/$TUN/configurations" "${H[@]}" \
  --data @/tmp/erp_demo_tunnel.json \
  | python3 -c 'import sys,json;d=json.load(sys.stdin);print("Tunnel ingress OK" if d["success"] else d["errors"])'

curl -s -X POST "$CFAPI/zones/$ZONE/purge_cache" "${H[@]}" \
  -d '{"hosts":["erp-demo.bah-ia.com.ar","erp-demo-db.bah-ia.com.ar"]}' \
  | python3 -c 'import sys,json;d=json.load(sys.stdin);print("Cache purge OK" if d["success"] else d["errors"])'
