import json, urllib.request, subprocess, sys

# 1) Secretos
sec = {}
for line in open('/home/edd/.cloudflare_secrets'):
    line = line.strip()
    if '=' in line and not line.startswith('#'):
        k, v = line.split('=', 1); sec[k] = v
acct = sec['CLOUDFLARE_ACCOUNT_ID']; tun = sec['CLOUDFLARE_TUNNEL_ID']
HDRS = {'X-Auth-Email': sec['CLOUDFLARE_EMAIL'],
        'X-Auth-Key': sec['CLOUDFLARE_GLOBAL_API_KEY'],
        'Content-Type': 'application/json'}
BASE = f'https://api.cloudflare.com/client/v4/accounts/{acct}/cfd_tunnel/{tun}/configurations'
TARGET = "http://eddos-web-server:80"

# 2) Hostnames desde nginx server_name (fuente autoritativa)
out = subprocess.check_output(
    "grep -rhE '^\\s*server_name' /home/edd/Proyectos/Edd-OS/server/nginx/conf.d/*.conf "
    "| sed -E 's/.*server_name\\s+//; s/;//' | tr ' ' '\\n' | grep -v '^$' | sort -u",
    shell=True).decode()
hosts = [h for h in out.split('\n') if h and h != 'localhost']
print(f"Hostnames a restaurar: {len(hosts)}")

# 3) GET config actual (preservar todo menos ingress)
req = urllib.request.Request(BASE, headers=HDRS)
cur = json.load(urllib.request.urlopen(req))
config = cur['result']['config']
print(f"Ingress ACTUAL (roto): {len(config.get('ingress', []))} reglas")

# 4) Reconstruir ingress: cada host -> nginx, + catch-all 404
config['ingress'] = [{"hostname": h, "service": TARGET} for h in hosts]
config['ingress'].append({"service": "http_status:404"})

if "--apply" not in sys.argv:
    print("\n--- DRY RUN (no aplica). Reglas que se pondrian: ---")
    for h in hosts: print(f"  {h} -> {TARGET}")
    print("  (catch-all) -> http_status:404")
    print("\nPara aplicar: agregar --apply")
    sys.exit(0)

# 5) PUT
body = json.dumps({"config": config}).encode()
put = urllib.request.Request(BASE, data=body, headers=HDRS, method='PUT')
res = json.load(urllib.request.urlopen(put))
if res.get('success'):
    print(f"\n✅ INGRESS RESTAURADO: {len(config['ingress'])} reglas ({len(hosts)} hostnames + catch-all)")
else:
    print("\n❌ ERROR:", json.dumps(res.get('errors'), indent=2))
