#!/usr/bin/env python3
"""
panel-namecheap-dns — change A records in bulk through the Namecheap API.

  panel-namecheap-dns list                       all domains in the account, whose DNS is at Namecheap, where they point
  panel-namecheap-dns point DOMAIN IP              set the A records of DOMAIN and www.DOMAIN to IP (other records stay)
  panel-namecheap-dns backup                     save every domain's DNS records to /root/.namecheap/backup-<time>/
  panel-namecheap-dns move OLD_IP NEW_IP         DRY RUN: show every record that would change
  panel-namecheap-dns move OLD_IP NEW_IP --apply really change them (backs up each domain first)
     options: --only a.com,b.com   --skip c.com   (EXCLUDE in the config is always skipped)

Config: /root/.namecheap/config  (API_USER=…, API_KEY=…, optional USER_NAME=…, EXCLUDE="a.com b.com")
The server's public IP must be whitelisted in Namecheap → Profile → Tools → API Access.
Only A records whose address is exactly OLD_IP change. MX, TXT, CNAME, redirects, TTLs and the email
setting (EmailType) are written back exactly as they were.
"""
import json, os, re, sys, time, urllib.parse, urllib.request, xml.etree.ElementTree as ET

CFG_FILE = '/root/.namecheap/config'
API = 'https://api.namecheap.com/xml.response'
NS = '{http://api.namecheap.com/xml.response}'
PAUSE = 3.2   # Namecheap allows ~20 calls/minute


def cfg():
    c = {}
    for line in open(CFG_FILE):
        m = re.match(r'\s*([A-Z_]+)\s*=\s*"?([^"\n]*)"?\s*$', line)
        if m: c[m.group(1)] = m.group(2).strip()
    if not c.get('API_USER') or not c.get('API_KEY'):
        sys.exit('missing API_USER / API_KEY in ' + CFG_FILE)
    c.setdefault('USER_NAME', c['API_USER'])
    c['EXCLUDE'] = set(c.get('EXCLUDE', '').split())
    return c


def public_ip():
    return urllib.request.urlopen('https://api.ipify.org', timeout=10).read().decode().strip()


_last = [0.0]
def call(c, command, **params):
    wait = PAUSE - (time.time() - _last[0])
    if wait > 0: time.sleep(wait)
    q = {'ApiUser': c['API_USER'], 'ApiKey': c['API_KEY'], 'UserName': c['USER_NAME'], 'ClientIp': c['IP'], 'Command': command}
    q.update(params)
    data = urllib.parse.urlencode(q).encode()
    for attempt in range(4):
        try:
            raw = urllib.request.urlopen(urllib.request.Request(API, data=data), timeout=60).read()
            break
        except Exception as e:
            if attempt == 3: raise
            time.sleep(10 * (attempt + 1))
    _last[0] = time.time()
    root = ET.fromstring(raw)
    if root.get('Status') != 'OK':
        errs = '; '.join((e.text or '').strip() for e in root.iter(NS + 'Error'))
        raise RuntimeError(errs or raw[:300].decode(errors='replace'))
    return root.find(NS + 'CommandResponse')


def split(domain):
    # Namecheap wants SLD + TLD (handles two-level TLDs like co.uk)
    parts = domain.split('.')
    two = {'co.uk', 'org.uk', 'me.uk', 'com.au', 'com.br', 'co.za', 'com.mx', 'co.nz', 'com.es', 'com.co'}
    if len(parts) > 2 and '.'.join(parts[-2:]) in two:
        return '.'.join(parts[:-2]), '.'.join(parts[-2:])
    return '.'.join(parts[:-1]), parts[-1]


def domains(c):
    out, page = [], 1
    while True:
        r = call(c, 'namecheap.domains.getList', PageSize='100', Page=str(page))
        for d in r.iter(NS + 'Domain'):
            out.append({'name': d.get('Name').lower(), 'ours': d.get('IsOurDNS') == 'true', 'expired': d.get('IsExpired') == 'true'})
        paging = r.find(NS + 'Paging')
        total = int(paging.find(NS + 'TotalItems').text) if paging is not None else len(out)
        if len(out) >= total: return out
        page += 1


def get_hosts(c, domain):
    sld, tld = split(domain)
    r = call(c, 'namecheap.domains.dns.getHosts', SLD=sld, TLD=tld)
    res = r.find(NS + 'DomainDNSGetHostsResult')
    hosts = [dict(h.attrib) for h in res.iter(NS + 'host')]
    return {'domain': domain, 'email_type': res.get('EmailType') or 'NONE', 'using_our_dns': res.get('IsUsingOurDNS') == 'true', 'hosts': hosts}


def set_hosts(c, domain, email_type, hosts):
    sld, tld = split(domain)
    p = {'SLD': sld, 'TLD': tld, 'EmailType': email_type}
    for i, h in enumerate(hosts, 1):
        p['HostName%d' % i] = h['Name']
        p['RecordType%d' % i] = h['Type']
        p['Address%d' % i] = h['Address']
        p['TTL%d' % i] = h.get('TTL') or '1800'
        if h['Type'] == 'MX': p['MXPref%d' % i] = h.get('MXPref') or '10'
    r = call(c, 'namecheap.domains.dns.setHosts', **p)
    ok = r.find(NS + 'DomainDNSSetHostsResult')
    if ok is None or ok.get('IsSuccess') != 'true':
        raise RuntimeError('setHosts did not confirm success')


def backup_dir():
    d = '/root/.namecheap/backup-' + time.strftime('%Y%m%d-%H%M%S')
    os.makedirs(d, mode=0o700, exist_ok=True)
    return d


def main():
    a = sys.argv[1:]
    if not a or a[0] in ('-h', '--help'): print(__doc__); return
    c = cfg(); c['IP'] = public_ip()
    only = set(); skip = set(c['EXCLUDE'])
    if '--only' in a: only = set(a[a.index('--only') + 1].lower().split(','))
    if '--skip' in a: skip |= set(a[a.index('--skip') + 1].lower().split(','))
    if a[0] == 'point' and len(a) >= 3:
        # A records for @ and www of one domain -> IP. Parking-page defaults are removed; mail and all other records stay.
        name, ip = a[1].lower(), a[2]
        if not re.match(r'^\d+\.\d+\.\d+\.\d+$', ip): sys.exit('IP must be an IPv4 address')
        if name in skip: sys.exit('%s is on the exclude list' % name)
        try: h = get_hosts(c, name)
        except Exception as e: sys.exit('Namecheap: %s' % e)
        if not h['using_our_dns']: sys.exit('%s does not use Namecheap DNS (custom nameservers), so its records cannot be set here' % name)
        json.dump(h, open(os.path.join(backup_dir(), name + '.json'), 'w'), indent=1)
        keep = [x for x in h['hosts'] if not (x['Name'] in ('@', 'www') and x['Type'] in ('A', 'AAAA', 'CNAME', 'URL', 'URL301', 'FRAME', 'ALIAS'))]
        new = keep + [{'Name': '@', 'Type': 'A', 'Address': ip, 'TTL': '300'}, {'Name': 'www', 'Type': 'A', 'Address': ip, 'TTL': '300'}]
        set_hosts(c, name, h['email_type'], new)
        chk = get_hosts(c, name)
        got = {x['Name'] for x in chk['hosts'] if x['Type'] == 'A' and x['Address'] == ip}
        if not {'@', 'www'} <= got: sys.exit('Namecheap did not confirm the change')
        print('%s and www.%s now point to %s (Namecheap)' % (name, name, ip)); return
    ds = domains(c)
    if only: ds = [d for d in ds if d['name'] in only]

    if a[0] == 'list':
        for d in ds:
            note = 'EXCLUDED' if d['name'] in skip else ('expired' if d['expired'] else ('' if d['ours'] else 'DNS elsewhere'))
            ip = ''
            if d['ours'] and not d['expired']:
                try:
                    h = get_hosts(c, d['name']); ip = ' '.join(sorted({x['Address'] for x in h['hosts'] if x['Type'] == 'A' and x['Name'] == '@'}))
                except Exception as e: ip = 'error: %s' % e
            print('%-28s %-16s %s' % (d['name'], ip, note), flush=True)
        print('%d domains' % len(ds)); return

    if a[0] == 'backup':
        bd = backup_dir(); n = 0
        for d in ds:
            if not d['ours'] or d['expired']: continue
            try: json.dump(get_hosts(c, d['name']), open(os.path.join(bd, d['name'] + '.json'), 'w'), indent=1); n += 1
            except Exception as e: print('  %s: %s' % (d['name'], e))
        print('backed up %d domains to %s' % (n, bd)); return

    if a[0] == 'move' and len(a) >= 3:
        old, new, apply = a[1], a[2], '--apply' in a
        if not re.match(r'^\d+\.\d+\.\d+\.\d+$', old) or not re.match(r'^\d+\.\d+\.\d+\.\d+$', new): sys.exit('OLD_IP and NEW_IP must be IPv4 addresses')
        bd = backup_dir() if apply else None
        changed = untouched = failed = 0
        print(('APPLYING' if apply else 'DRY RUN (nothing changes; add --apply)') + ': A records %s -> %s' % (old, new), flush=True)
        for d in ds:
            name = d['name']
            if name in skip: print('  %-28s skipped (excluded)' % name, flush=True); continue
            if d['expired']: print('  %-28s skipped (expired)' % name, flush=True); continue
            if not d['ours']: print('  %-28s skipped (DNS not at Namecheap)' % name, flush=True); continue
            try:
                h = get_hosts(c, name)
                hits = [x for x in h['hosts'] if x['Type'] == 'A' and x['Address'] == old]
                if not hits: untouched += 1; print('  %-28s no record on %s' % (name, old), flush=True); continue
                labels = ', '.join(x['Name'] for x in hits)
                if not apply: changed += 1; print('  %-28s would change: %s' % (name, labels), flush=True); continue
                json.dump(h, open(os.path.join(bd, name + '.json'), 'w'), indent=1)
                new_hosts = [dict(x, Address=new) if (x['Type'] == 'A' and x['Address'] == old) else x for x in h['hosts']]
                set_hosts(c, name, h['email_type'], new_hosts)
                check = get_hosts(c, name)
                left = [x for x in check['hosts'] if x['Type'] == 'A' and x['Address'] == old]
                if left or len(check['hosts']) != len(h['hosts']): raise RuntimeError('verification failed after update')
                changed += 1; print('  %-28s CHANGED: %s' % (name, labels), flush=True)
            except Exception as e:
                failed += 1; print('  %-28s FAILED: %s' % (name, e), flush=True)
        print('%s: %d %s, %d without %s, %d failed%s' % ('done' if apply else 'dry run', changed, 'changed' if apply else 'would change',
                                                        untouched, old, failed, ('  (backup: %s)' % bd) if bd else ''))
        return
    print(__doc__)


if __name__ == '__main__':
    main()
