#!/usr/bin/env python3
# Copyright 2019 Oliver Smith
# SPDX-License-Identifier: GPL-3.0-or-later

import argparse
import glob
import os
import sys
import urllib.request
import json


def get_devices():
    """:returns: list of all devices"""
    ret = []
    pmaports = (os.path.realpath(os.path.join(os.path.dirname(__file__) +
                "/..")))
    for path in glob.glob(pmaports + "/device/device-*/"):
        device = os.path.dirname(path).split("device-", 1)[1]
        ret.append(device)
    return sorted(ret)

def get_wiki_devices_api(path):
    content = ""
    if path:
        # Read file
        with open(path, encoding="utf-8") as handle:
            content = handle.read()
    else:
        # Download data from API
        url = "https://wiki.postmarketos.org/api.php?action=cargoquery&limit=500&tables=Devices&format=json&fields=CONCAT(_pagename,'%20',Name,'%20',Codename)=names,Booting&order_by=Devices.Manufacturer,Devices.Name&where=Booting=1"
        content = urllib.request.urlopen(url).read().decode("utf-8")
        # Make data easier to handle
    decoded = json.loads(content)["cargoquery"]
    decoded = list(map(lambda x: x["title"], decoded))

    return(decoded)
    
def get_gitlab_merge_requests():
    url = "https://gitlab.com/api/v4/projects/8065375/merge_requests?scope=all"
    content = urllib.request.urlopen(url).read().decode("utf-8")
    decoded = json.loads(content)
    #print(decoded)
    
    return(decoded)
    

def check_device(device, json_data, is_booting):
    """:param is_booting: require the device to be in the booting section, not
                          just anywhere in the page (i.e. in the not booting
                          table).
       :returns: True when the device is in the appropriate section."""

    for tested_device in json_data:
        if device in tested_device["names"]:
            if tested_device["Booting"] == "1":
                return True
            else:
                print(device + ": still in 'not booting' section (if this is a"
                  " merge request, your device should be in the booting"
                  " section already)")
                return False

    print(device + ": not in the wiki yet.")
    return False
    
def check_device_uno_reverse(device, git_data, is_booting, merge_requests):
    #print(device)
    for tested_device in git_data:
        #print(tested_device)
        if tested_device in device["names"]:
            if device["Booting"] == "1":
                return True
            else:
                print(device["names"] + ": still in 'not booting' section, wiki style")
                return False
                
    for tested_device in git_data:
        for merge_data in merge_requests:
            if tested_device in merge_data["title"]:
                print(device["names"] + "\t\t\tin MR")
                return True
            
    print(device["names"] + ":\t\t\t\t\tNOT ON GIT SOMEHOW")
    return False

def main():
    # Parse arguments
    parser = argparse.ArgumentParser()
    parser.add_argument("--booting", help="devices must be in the upper table,"
                        " being in the 'not booting' table below is not"
                        " enough (all devices in pmaports master and stable"
                        " branches and should be in the upper table)",
                        action="store_true")
    parser.add_argument("--path", help="instead of downloading the devices"
                        " page from the wiki, use a local HTML file",
                        default=None)
    args = parser.parse_args()

    # Check all devices
    json_data = get_wiki_devices_api(args.path)
    error = False
    for device in get_devices():
        if not check_device(device, json_data, args.booting):
            error = True
    merge_requests = get_gitlab_merge_requests()
    print("2nd")
    for device in json_data:
        check_device_uno_reverse(device, get_devices(), args.booting, merge_requests)

    # Ask to adjust the wiki
    if error:
        print("*** Wiki check failed!")
        print("Thank you for porting postmarketOS to a new device! \o/")
        print("")
        print("Now it's time to add some documentation:")
        print("1) Create a device specific wiki page as described here:")
        print("   <https://wiki.postmarketos.org/wiki/Help:Device_Page>")
        print("2) Set 'booting = yes' in the infobox of your device page.")
        print("3) Run these tests again with an empty commit in your MR:")
        print("   $ git commit --allow-empty -m 'run tests again'")
        print("")
        print("Please take the time to do these steps. It will make your")
        print("precious porting efforts visible for others, and allow them")
        print("not only to use what you have created, but also to build upon")
        print("it more easily. Many times one person did a port with basic")
        print("functionality, and then someone else jumped in and")
        print("contributed major new features.")
        return 1
    else:
        print("*** Wiki check successful!")
    return 0


sys.exit(main())
