#!/usr/bin/env python3
"""Set up dl.minproducerdn.com: DNS A record + DDNS entry + Caddy site block."""
import json, subprocess, sys, urllib.request

sys.stdout.reconfigure(encoding='utf-8')

CFG = '/home/minproducer/cloudflare-ddns/config.json'
CADDY = '/home/minproducer/n8n/Caddyfile'
DOMAIN = 'dl.minproducerdn.com'
IP = '171.238.152.56'

cfg = json.load(open(CFG))
token = cfg['api_token']
zone = cfg['zone_id']

# 1. create the DNS A record (DNS only)
req = urllib.request.Request(
    'https://api.cloudflare.com/client/v4/zones/%s/dns_records' % zone,
    data=json.dumps({'type': 'A', 'name': DOMAIN, 'content': IP, 'ttl': 300, 'proxied': False}).encode(),
    headers={'Authorization': 'Bearer %s' % token, 'Content-Type': 'application/json'},
    method='POST')
resp = json.load(urllib.request.urlopen(req, timeout=30))
if resp.get('success'):
    print('DNS record created:', resp['result']['name'], '->', resp['result']['content'])
else:
    errs = resp.get('errors', [])
    if any('already exists' in str(e) for e in errs):
        print('DNS record already exists - ok')
    else:
        print('DNS ERROR:', errs)
        sys.exit(1)

# 2. add to the DDNS domain list
if DOMAIN not in cfg['domains']:
    cfg['domains'].append(DOMAIN)
    json.dump(cfg, open(CFG, 'w'), indent=2)
    print('DDNS config updated (%d domains)' % len(cfg['domains']))
else:
    print('DDNS config already has the domain')

# 3. Caddy site block
s = open(CADDY).read()
if 'dl.minproducerdn.com' in s:
    print('Caddy block already exists')
else:
    s += '\ndl.minproducerdn.com {\n\treverse_proxy 192.168.1.3:8080\n}\n'
    open(CADDY, 'w').write(s)
    print('Caddy site block appended')
