import json, urllib.request, sys

# Uso: python3 add-tunnel-hostname.py <hostname> <service-url>
# Hace MERGE seguro: GET config, inserta/actualiza la regla antes del catch-all, PUT.
if len(sys.argv) < 3:
    print("Uso: add-tunnel-hostname.py <hostname> <service>"); sys.exit(1)
HOST, SERVICE = sys.argv[1], sys.argv[2]

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'

cur = json.load(urllib.request.urlopen(urllib.request.Request(BASE, headers=HDRS)))
config = cur['result']['config']
ingress = config.get('ingress', [])

# separar reglas con hostname del catch-all
rules = [r for r in ingress if 'hostname' in r and r.get('hostname') != HOST]
catch = next((r for r in ingress if 'hostname' not in r), {"service": "http_status:404"})
rules.append({"hostname": HOST, "service": SERVICE})
config['ingress'] = rules + [catch]

put = urllib.request.Request(BASE, data=json.dumps({"config": config}).encode(), headers=HDRS, method='PUT')
res = json.load(urllib.request.urlopen(put))
print(f"{'✅ OK' if res.get('success') else '❌ ERROR'} — {HOST} -> {SERVICE} | ingress total: {len(config['ingress'])}")
if not res.get('success'):
    print(json.dumps(res.get('errors'), indent=2))
