#!/usr/bin/env python3
# elite-updater-mirrors [DIR...]: the launcher self-update description (updater.json) for every mirror, updater-<host>.json
# (nginx serves it as /elite/dl/updater.json there; Moscow asks for updater-dow2ru.fintebtc.de.json).
# Every mirror links to its own files. The Russian mirror comes first by the launcher own endpoint order (1.3.3+: dow2ru,
# dow2, rts): where Moscow does not answer, the launcher asks the next mirror and downloads from there. (29.10 evening: all
# mirrors linking to Moscow hung the update for players who cannot reach Russian hosting - Ukraine.)
# Run on every release and by elite-updater-mirrors.timer every 2 minutes.
import json, os, re, sys, urllib.request
dirs = sys.argv[1:] or ["/var/www/rts-site/elite/dl", "/mnt/ssd/eliteupd/store3/dl"]
RU = "dow2ru.fintebtc.de"
def ok(url):
    try:
        r = urllib.request.urlopen(urllib.request.Request(url, method="HEAD", headers={"User-Agent": "elite-updater-check"}), timeout=15)
        return r.status == 200
    except Exception: return False
for d in dirs:
    try: u = json.load(open(os.path.join(d, "updater.json")))
    except Exception: continue
    plats = u.get("platforms", {})
    ru_up = bool(plats) and all(ok(re.sub(r"^https://[^/]+/", "https://%s/" % RU, p["url"])) for p in {p["url"]: p for p in plats.values()}.values())
    for host in (RU, "dow2.fintebtc.de", "rts.fintebtc.de"):
        target = host
        v = json.loads(json.dumps(u))
        for p in v["platforms"].values(): p["url"] = re.sub(r"^https://[^/]+/", "https://%s/" % target, p["url"])
        out = os.path.join(d, "updater-%s.json" % host); new = json.dumps(v, indent=1)
        try: old = open(out).read()
        except Exception: old = ""
        if new != old:
            open(out + ".tmp", "w").write(new); os.chmod(out + ".tmp", 0o644); os.replace(out + ".tmp", out)
            print("%s: %s links -> %s" % (d, host, target))
