#!/usr/bin/env python3
# This file is automatically generated by fs-package

import hashlib
import os
import sys


def verify(archive: str, h, checksum):
    with open(archive, "rb") as f:
        actual_checksum = h(f.read()).hexdigest()
    result = actual_checksum == checksum
    if result:
        print("Checksum verified")
    else:
        print("Checksum verification failed")
        print("Expected", checksum)
        print("But got:", actual_checksum)
    return result


def main():
    url = sys.argv[1]
    checksum = sys.argv[2]

    if checksum.startswith("sha256:"):
        h = hashlib.sha256
        checksum = checksum[7:]
    else:
        raise Exception("Unknown hash function")

    archive = url.split("/")[-1]
    if not os.path.exists("build/env/_sources"):
        os.makedirs("build/env/_sources")
    archive = os.path.join("build/env/_sources", archive)

    if os.path.exists(archive):
        if verify(archive, h, checksum):
            sys.exit(0)
        print("Removing archive", archive)
        os.remove(archive)

    # FIXME: Replace use of wget, just use python instead
    if os.system(f'cd build/env/_sources && wget "{url}"') != 0:
        print("Failed to download")
        sys.exit(1)

    if not verify(archive, h, checksum):
        sys.exit(2)


if __name__ == "__main__":
    main()
