#!/usr/bin/env python3
"""Copies the winget manifests attached to EdgeLink's GitHub releases into the directory that
rewinged serves. Run periodically; releases that are already present are skipped."""

import json
import os
import re
import sys
import urllib.request

REPO = "xelossan/EdgeLink"
PACKAGE = "xelossan.EdgeLink"
ASSET = PACKAGE + ".yaml"
TARGET = os.environ.get("REWINGED_MANIFESTS", "/var/lib/rewinged/manifests")
INSTALLER_PREFIX = "https://github.com/%s/releases/download/" % REPO


def fetch(url):
    request = urllib.request.Request(url, headers={"User-Agent": "rewinged-sync", "Accept": "application/vnd.github+json"})
    with urllib.request.urlopen(request, timeout=30) as response:
        return response.read()


def main():
    releases = json.loads(fetch("https://api.github.com/repos/%s/releases?per_page=50" % REPO))
    added = 0

    for release in releases:
        tag = release.get("tag_name", "")
        if release.get("draft") or not re.fullmatch(r"v\d+(\.\d+){1,3}", tag):
            continue

        directory = os.path.join(TARGET, "xelossan", "EdgeLink", tag[1:])
        path = os.path.join(directory, ASSET)
        if os.path.exists(path):
            continue

        asset = next((a for a in release.get("assets", []) if a.get("name") == ASSET), None)
        if asset is None:
            continue

        text = fetch(asset["browser_download_url"]).decode("utf-8")

        # the manifest tells winget what to download and run, so refuse anything unexpected
        urls = re.findall(r"^\s*InstallerUrl:\s*(\S+)\s*$", text, re.MULTILINE)
        if ("PackageIdentifier: %s\n" % PACKAGE) not in text \
                or ("PackageVersion: %s\n" % tag[1:]) not in text \
                or not urls or not all(u.startswith(INSTALLER_PREFIX + tag + "/") for u in urls):
            print("Skipping %s: manifest does not look right" % tag, file=sys.stderr)
            continue

        os.makedirs(directory, exist_ok=True)
        temporary = path + ".tmp"
        with open(temporary, "w", encoding="utf-8", newline="\n") as file:
            file.write(text)
        os.replace(temporary, path)
        print("Added %s" % tag)
        added += 1

    print("Done, %d new" % added)


if __name__ == "__main__":
    main()
