import base64
import hashlib
import json
import pathlib
import re
import subprocess

import requests

url = "https://storage.googleapis.com/kubernetes-release/release/v{version}/bin/linux/{arch}/{pname}"  # noqa E501

hashes = {}

hashes_file = pathlib.Path("hashes.json")

if hashes_file.exists():
    hashes = json.loads(hashes_file.read_bytes())

stable = {}
tags = subprocess.run(
    ["git", "ls-remote", "--tags", "https://github.com/kubernetes/kubernetes"],
    capture_output=True,
)
tag_re = re.compile(rb"refs/tags/v(\d+)\.(\d+)\.(\d+)$", re.MULTILINE)
start = 0
while start < len(tags.stdout):
    if match := tag_re.search(tags.stdout, pos=start):
        start = match.end()
        major = int(match.group(1))
        minor = int(match.group(2))
        if minor < 22:
            continue
        patch = int(match.group(3))
        key = (major, minor)
        if key in stable:
            stable[key] = max(patch, stable[key])
        else:
            stable[key] = patch
    else:
        break

for pname in ["kubeadm", "kubectl", "kubelet"]:
    if pname not in hashes:
        hashes[pname] = {}
    for arch in ["amd64", "arm64"]:
        if arch not in hashes[pname]:
            hashes[pname][arch] = {}
        for major, minor in stable.keys():
            patch_max = stable[(major, minor)]
            for patch in range(0, patch_max + 1):
                version = f"{major}.{minor}.{patch}"
                if version in hashes[pname][arch]:
                    continue
                url = f"https://dl.k8s.io/release/v{version}/bin/linux/{arch}/{pname}"  # noqa E501
                try:
                    r = requests.get(url)
                    hash = "sha256-" + base64.b64encode(
                        hashlib.sha256(r.content).digest()
                    ).decode("ascii")
                    hashes[pname][arch][version] = hash
                    print(pname, arch, version, hash)

                    hashes_file.write_text(
                        json.dumps(hashes, indent=2, sort_keys=True), encoding="utf-8"
                    )
                except Exception as e:
                    print(e)