#!/usr/bin/python3

import sys
import os
import argparse
import lsb_release
import platform
import tempfile
import requests
import json
from pkg_resources import parse_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)

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():
                print(release)
                return release["version"]
        return None

def get_firefox_version_json(which="stable"):
    mrv = parse_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 = parse_version(release["version"])

            if which == "esr" and version > parse_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 = parse_version(release["version"])
            if version > mrv:
                mrv = version
                mrr = release_name
    return mrr.replace("firefox-", "")

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("")

parser = argparse.ArgumentParser(description="Download and install a browser for testing")
parser.add_argument("browser", metavar="firefox|chromium", type=str, help="Specify a browser", nargs=1)
parser.add_argument("-v", "--version", type=str, help="Specify a version or 'stable' or 'beta' ('stable' is the default)")
args = parser.parse_args()

browser = args.browser[0]

if browser == "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 browser == "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
else:
    version = args.version

firefox_mint_to_ubuntu = {
    "victoria" : "jammy",
    "vera" : "jammy",
    "vanessa" : "jammy",
    "una" : "focal",
    "uma" : "focal",
    "tricia" : "bionic"
}

chromium_codename_to_image_map = {
    "elsie" : "lmde5",
    "debbie" : "lmde4",
    "una" : "mint20",
    "vera": "mint21",
    "victoria": "mint21",
    "vanessa": "mint21"
}

try:
    codename = lsb_release.get_os_release()["CODENAME"]
except:
    codename = lsb_release.get_lsb_information()["CODENAME"]

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 (("","linuxmint1"), ("-beta", "beta")):
    if browser == "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+linuxmint1+%s_%s.tar" % (version, codename, arch)
            tarpath = os.path.join(path_to_tar, tarfile)
        elif codename in lmde.keys():
            root_folder = "firefox-lmde%s" % suffix
            path_to_tar = os.path.join(root_folder, "linuxmintd_%s-%s" % (lmde[codename], arch))
            tarfile = "bundle-%s~linuxmint1+%s_%s.tar" % (version, codename, arch)
            tarpath = os.path.join(path_to_tar, tarfile)

    elif browser == "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 browser == "firefox":
                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 browser == "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)
