#!/usr/bin/env python3


from sys import argv, exit

from requests import get

try:
    # Arch Linux (possibly future Ubuntu releases)
    from packaging.version import parse
except ModuleNotFoundError:
    # Debian
    from setuptools._vendor.packaging.version import parse


assert (
    len(argv) >= 3
), "Usage: check_pypi_for_new_release <project> <version> [tag prefix]"

repo = argv[1]
current_version = argv[2]
if len(argv) >= 4:
    tag_prefix = argv[3]
else:
    tag_prefix = ""

try:
    r = get(
        "https://pypi.org/pypi/{}/json".format(repo),
        headers={"Accept": "application/json"},
    )
    r.raise_for_status()

    releases = r.json()['releases']

    newest_release = None

    for version, info in releases.items():
        if version.startswith(tag_prefix):
            if newest_release is None or parse(version) > parse(newest_release):
                newest_release = version

    assert newest_release is not None, "Could not determine latest release"

    if parse(newest_release) > parse(current_version):
        print(
            "There is a newer version available: {} (currently installed: {})".format(
                newest_release, current_version
            )
        )

        exit(2)
    else:
        print("Currently installed version {} matches newest release on PyPI".format(current_version))
        exit(0)
except Exception as e:
    print(repr(e))
    exit(3)