#!/usr/bin/python3

import sys
import os
import argparse
import csv
import platform
import tempfile
import requests
import json
from packaging.version import Version

from gi.repository import Gio, GLib

IP = "135.181.5.124"

chromium_resp = requests.get("https://chromiumdash.appspot.com/fetch_releases?num=1", timeout=30)
chromium_json = json.loads(chromium_resp.text)

firefox_resp = requests.get("https://product-details.mozilla.org/1.0/firefox.json", timeout=30)
firefox_json = json.loads(firefox_resp.text)

thunderbird_resp = requests.get("https://product-details.mozilla.org/1.0/thunderbird.json", timeout=30)
thunderbird_json = json.loads(thunderbird_resp.text)

def get_chromium_version(which="stable"):
        if which not in ("stable", "beta"):
            return None
        for release in chromium_json:
            if release["platform"] == "Linux" and release["channel"] == which.capitalize():
                return release["version"]
        return None

def get_firefox_version_json(which="stable"):
    mrv = Version("0")
    mrr = ""
    releases = firefox_json["releases"]
    for release_name in releases.keys():
        if which == "esr" and "esr" not in release_name:
            continue
        elif which != "esr" and "esr" in release_name:
            continue
        release = releases[release_name]
        if which in ("stable", "esr"):
            if release["category"] not in ("major", "stability"):
                continue
            if "b" in release["version"]:
                continue
            version = Version(release["version"])

            if which == "esr" and version > Version("79.0.0"):
                continue

            if version > mrv:
                mrv = version
                mrr = release_name
        elif which == "beta":
            if release["category"] != "dev":
                continue
            if "b" not in release["version"]:
                continue
            version = Version(release["version"])
            if version > mrv:
                mrv = version
                mrr = release_name
    return mrr.replace("firefox-", "")

def get_thunderbird_version_json(which="esr"):
    res = requests.get("https://product-details.mozilla.org/1.0/thunderbird.json", timeout=30)
    tbird_json = json.loads(res.text)

    mrv = Version("0")
    mrr = ""
    version = None

    releases = tbird_json["releases"]
    for release_name in releases.keys():
        release = releases[release_name]
        if which == "esr":
            if release_name.endswith("esr") and release["category"] in ("major", "stability"):
                version = Version(release["version"])
        elif which == "stable":
            if release["category"] == "stability":
                version = Version(release["version"])
        elif which == "beta":
            if release["category"] == "dev":
                version = Version(release["version"])
        if version is not None and version > mrv:
            mrv = version
            mrr = release_name
    return mrr.replace("thunderbird-", "")

print("")
print("Current STABLE Firefox version is %s" % get_firefox_version_json("stable"))
print("Current BETA Firefox version is %s" % get_firefox_version_json("beta"))
print("")
print("Current STABLE Chromium version is %s" % get_chromium_version("stable"))
print("Current BETA Chromium version is %s" % get_chromium_version("beta"))
print("")
print("Current LTS Thunderbird version is %s" % get_thunderbird_version_json("esr"))
print("")

parser = argparse.ArgumentParser(description="Download and install an application for testing")
parser.add_argument("app", metavar="firefox|chromium|thunderbird", type=str, help="Specify an application", nargs=1)
parser.add_argument("-v", "--version", type=str, help="Specify a version or 'stable', 'beta' or 'esr' ('stable' is the default for all but Thunderbird, which is 'esr'")
parser.add_argument("-r", "--release", type=str, help="Specify a Mint release like vera or una (default is taken from host)")
parser.add_argument("-b", "--buildid", type=str, help="Build ID (linuxmint1, etc...) Defaults to linuxmint1", default="linuxmint1")
args = parser.parse_args()

app = args.app[0]

if app == "chromium":
    if args.version in (None, "stable"):
        version = get_chromium_version("stable")
    elif args.version == "beta":
        version = get_chromium_version("beta")
    else:
        version = args.version
elif app == "firefox":
    if args.version in (None, "stable"):
        version = get_firefox_version_json("stable")
    elif args.version == "beta":
        version = get_firefox_version_json("beta")
    else:
        version = args.version
elif app == "thunderbird":
    if args.version in (None, "esr"):
        version = get_thunderbird_version_json("esr")
    else:
        version = args.version
else:
    version = args.version

firefox_mint_to_ubuntu = {
    "zara"   : "noble",
    "xia"   : "noble",
    "wilma" : "noble",
    "virginia" : "jammy",
    "victoria" : "jammy",
    "vera" : "jammy",
    "vanessa" : "jammy",
    "una" : "focal",
    "uma" : "focal",
    "tricia" : "bionic"
}

chromium_codename_to_image_map = {
    "gigi" : "lmde7",
    "faye" : "lmde6",
    "elsie" : "lmde5",
    "debbie" : "lmde4",
    "una" : "mint20",
    "vera": "mint21",
    "virginia": "mint21",
    "victoria": "mint21",
    "vanessa": "mint21",
    "wilma": "mint22",
    "xia"  : "mint22",
    "zara"  : "mint22"
}

if args.release:
    codename = args.release
else:
    os_release = {}
    with open("/etc/os-release") as f:
        reader = csv.reader(f, delimiter="=")
        os_release = dict(reader)

    try:
        codename = os_release["VERSION_CODENAME"]
    except KeyError:
        print("Autodetected codename not valid, provide one using -r")
        sys.exit(1)

arch_info = platform.architecture()

if arch_info[0] == "64bit":
    arch = "amd64"
elif arch_info[0] == "32bit":
    arch = "i386"

tarfile = None
tarpath = None

deb = None
deb_dbg = None

success = False

for suffix, release_id in (("", args.buildid), ("-beta", "beta")):
    if app == "firefox":
        if codename in firefox_mint_to_ubuntu.keys():
            root_folder = "firefox-mint%s" % suffix
            path_to_tar = os.path.join(root_folder, "firefox_%s-%s" % (firefox_mint_to_ubuntu[codename], arch))
            tarfile = "bundle-%s+%s+%s_%s.tar" % (version, release_id, codename, arch)
            tarpath = os.path.join(path_to_tar, tarfile)
        elif codename in chromium_codename_to_image_map.keys():
            root_folder = "firefox-lmde%s" % suffix
            path_to_tar = os.path.join(root_folder, "linuxmintd_%s-%s" % (chromium_codename_to_image_map[codename], arch))
            tarfile = "bundle-%s~%s+%s_%s.tar" % (version, release_id, codename, arch)
            tarpath = os.path.join(path_to_tar, tarfile)

    elif app == "thunderbird":
        if codename in firefox_mint_to_ubuntu.keys():
            root_folder = "thunderbird-mint%s" % suffix
            path_to_tar = os.path.join(root_folder, "thunderbird_%s-%s" % (firefox_mint_to_ubuntu[codename], arch))
            tarfile = "bundle-%s+%s+%s_%s.tar" % (version, release_id, codename, arch)
            tarpath = os.path.join(path_to_tar, tarfile)

    elif app == "chromium":
        root_folder = "chromium%s" % suffix
        if codename in chromium_codename_to_image_map.keys():
            if arch == "i386":
                root_folder = "chromium-lmde"
            path_to_debs = os.path.join(root_folder, "linuxmintd_%s-%s" % (chromium_codename_to_image_map[codename], arch))
            deb = os.path.join(path_to_debs, "chromium_%s~%s+%s_%s.deb" % (version, release_id, codename, arch))
            deb_dbg = os.path.join(path_to_debs, "chromium-dbg_%s~%s+%s_%s.deb" % (version, release_id, codename, arch))

    with tempfile.TemporaryDirectory() as dirname:
        def call(command):
            return_code = os.system(command)
            if return_code != 0:
                raise Exception("Command '%s' failed..." % command)

        try:
            if app in ("firefox", "thunderbird"):
                call("wget -P %s %s" % (dirname, os.path.join(IP, tarpath)))
                os.chdir(dirname)
                call("tar xf %s" % tarfile)
                call("sudo dpkg -i *.deb")
            elif app == "chromium":
                call("wget -P %s %s" % (dirname, os.path.join(IP, deb)))
                call("wget -P %s %s" % (dirname, os.path.join(IP, deb_dbg)))
                os.chdir(dirname)
                call("sudo dpkg -i *.deb")
            break
        except Exception as e:
            print(e)
            continue

sys.exit(0)
