#!/usr/bin/env python3
"""Export Cloudflare tunnel configurations + every zone's DNS records (+ zone settings) as JSON into $1 (staging dir for the crystalcave restic job).
Read-only API calls with the account token in ~/.hermes/state/cloudflare.env (never printed). Failures print a WARN and exit 0 so the backup still runs."""
import json, os, sys, urllib.request
out = sys.argv[1]; os.makedirs(out, exist_ok=True)
env = dict(l.strip().split('=', 1) for l in open('/home/canutethegreat/.hermes/state/cloudflare.env') if '=' in l and not l.startswith('#'))
tok, acct = env['CLOUDFLARE_API_TOKEN'], env['CLOUDFLARE_ACCOUNT_ID']
def get(path):
    r = urllib.request.Request('https://api.cloudflare.com/client/v4' + path, headers={'Authorization': 'Bearer ' + tok})
    return json.load(urllib.request.urlopen(r, timeout=60))
def pages(path):
    res, p = [], 1
    while True:
        d = get(f'{path}{"&" if "?" in path else "?"}per_page=100&page={p}'); res += d['result']
        if p >= d.get('result_info', {}).get('total_pages', 1): return res
        p += 1
n = 0
try:
    tun = pages(f'/accounts/{acct}/cfd_tunnel?is_deleted=false')
    for t in tun:
        t['configuration'] = get(f'/accounts/{acct}/cfd_tunnel/{t["id"]}/configurations')['result']
    json.dump(tun, open(out + '/tunnels.json', 'w'), indent=1); n += 1
except Exception as e: print('WARN: tunnel export failed:', e.__class__.__name__, str(e)[:100])
try:
    for z in pages('/zones'):
        recs = pages(f'/zones/{z["id"]}/dns_records')
        json.dump({'zone': z, 'dns_records': recs}, open(f'{out}/zone-{z["name"]}.json', 'w'), indent=1); n += 1
except Exception as e: print('WARN: zone export failed:', e.__class__.__name__, str(e)[:100])
print('cloudflare export files:', n)
