#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
Root & Branch Register — mirror.

Fetches a complete copy of the Register and the day's digest, then hands both
to verify.py. Standard library only; no account, no key, no agreement with the
Registrar (§17.2).

    python3 mirror.py [base-url] [destination]

Defaults to https://rootandbranchregister.org and ./rbr-mirror.
"""
import json, os, sys, urllib.request

def get(url):
    with urllib.request.urlopen(url, timeout=60) as r:
        return r.read()

def main(argv):
    base = (argv[1] if len(argv) > 1 else "https://rootandbranchregister.org").rstrip("/")
    dest = argv[2] if len(argv) > 2 else "./rbr-mirror"
    os.makedirs(dest, exist_ok=True)

    manifest = json.loads(get(base + "/register/export.json"))
    day, root = manifest["generated"], manifest["root"]
    print("day  %s\nroot %s\nfiles %d" % (day, root, len(manifest["files"])))

    export = os.path.join(dest, "export")
    for f in manifest["files"]:
        name = f["name"]                      # "<kind>/<identifier>"
        p = os.path.join(export, name + ".txt")
        os.makedirs(os.path.dirname(p), exist_ok=True)
        open(p, "wb").write(get(base + "/export/" + name + ".txt"))
        print("  " + name)

    dg = os.path.join(dest, "latest.txt")
    open(dg, "wb").write(get(base + "/digest/latest.txt"))
    open(os.path.join(dest, "verify.py"), "wb").write(get(base + "/register/tools/verify.py"))
    print("\nMirrored to %s\nNow run:\n  python3 %s %s %s"
          % (dest, os.path.join(dest, "verify.py"), export, dg))
    return 0

if __name__ == "__main__":
    sys.exit(main(sys.argv))
