#!/usr/bin/python3

import sys
import os
from gi.repository import GLib

GROUP = "Mint Development Tools"
SANDBOX_PATH = "DevRoot"
SANDBOX_NAME = "RootDisplayName"
THREADS = "Threads"

SETTINGS_PATH = "%s/mint-dev-tools" % GLib.get_user_config_dir()

settings = None


class Project:

    def __init__(self, name, subprojects):
        self.name = name
        self.subprojects = subprojects

projects = []
projects.append(Project("Cinnamon (all sub-projects)", ["cinnamon-translations", "cinnamon-desktop", "cinnamon-menus",
                                                        "cinnamon-session", "cinnamon-settings-daemon", "cinnamon-screensaver", "cjs",
                                                        "cinnamon-control-center", "muffin",
                                                        "cinnamon", "nemo", "xapps"]))
projects.append(Project("cjs", ["cjs"]))
projects.append(Project("cinnamon-desktop", ["cinnamon-desktop"]))
projects.append(Project("cinnamon-menus", ["cinnamon-menus"]))
projects.append(Project("cinnamon-translations", ["cinnamon-translations"]))
projects.append(Project("cinnamon-session", ["cinnamon-session"]))
projects.append(Project("cinnamon-settings-daemon", ["cinnamon-settings-daemon"]))
projects.append(Project("cinnamon-control-center", ["cinnamon-control-center"]))
projects.append(Project("cinnamon-Screensaver", ["cinnamon-screensaver"]))
projects.append(Project("muffin", ["muffin"]))
projects.append(Project("cinnamon", ["cinnamon"]))
projects.append(Project("nemo", ["nemo"]))
projects.append(Project("nemo-extensions", ["nemo-extensions"]))
projects.append(Project("mdm", ["mdm"]))
projects.append(Project("xapps", ["xapps"]))

simple_projects = ['mintupdate', 'mintsources', 'mintlocale', 'mintsystem', 'mintmenu', 'mint-translations', 'mint-common', 'mint-x-icons', 'mintwelcome', 'mintdesktop', 'cinnamon-themes', 'mintstick', 'mintdrivers', 'mintinstall', 'mintnanny', 'mintupload', 'blueberry', 'mint-themes', 'mint-themes-gtk3']
for simple_project in simple_projects:
    projects.append(Project(simple_project, [simple_project]))

projects = sorted(projects, key=lambda x: x.name, reverse=False)

## Check mint-dev-setup ran successfully
if not os.path.exists(SETTINGS_PATH):
    print("")
    print(" === ERROR ===")
    print("")
    print("Your development environment isn't set up properly. Please run mint-dev-setup.")
    sys.exit(1)

settings = GLib.KeyFile.new()
settings.load_from_file(SETTINGS_PATH, GLib.KeyFileFlags.KEEP_COMMENTS)

root = settings.get_string(GROUP, SANDBOX_PATH)
name = settings.get_string(GROUP, SANDBOX_NAME)
threads = settings.get_integer(GROUP, THREADS)

print("")
print(" === WARNING ===")
print("")
print("This command does the following:")
print("    - Deletes all build outputs in your Sandbox (~/%s/*_*)" % name)
print("    - Deletes the local version (along with any local changes) for the selected project(s) (~/%s/<projectname>)" % name)
print("    - Downloads and compiles the selected project(s) from Github's master branch(es)")
print("    - Installs the packages produced by the compilation (and overrides local versions)")
print("")
print("If you're scared when reading any of that, PRESS CTRL+C NOW! Otherwise.. press ENTER to continue.")
input("")

selected_project = None

while selected_project is None:
    print("")
    print(" === PROJECT SELECTION ===")
    print("")
    print("Choose the project you'd like to build (note that this will overwrite the version running on your system):")
    print("")
    i = 1
    while i <= len(projects):
        project = projects[i - 1]
        print("  %d. %s" % (i, project.name))
        i += 1
    print("")

    index = 0
    try:
        index = int(input("Please type the number of the project you'd like to build: "))
    except:
        print("Invalid choice")
        sys.exit(1)
    if index > 0 and index <= len(projects):
        selected_project = projects[index - 1]

os.chdir(root)
os.system("rm -f *_*")  # Remove all packages and build results

def removeProject(subproject):
    if os.path.exists(subproject):
        print("")
        print("   #######################################################################")
        print("   ### Removing local version of %s" % subproject)
        print("   #######################################################################")
        print("")
        os.system("rm -rf %s" % subproject)

def cloneProject(subproject):
    print("")
    print("   #######################################################################")
    print("   ### Downloading %s" % subproject)
    print("   #######################################################################")
    print("")
    os.system("git clone https://github.com/linuxmint/%s.git" % subproject)

def buildProject(subproject, root, recursion = 0):
    subprojectPath = os.path.join(root, subproject)

    # If we are iterating items in a directory because there's no debian file,
    # filter files here, otherwise the files won't exist yet from the top level
    # because the project hasn't been cloned yet
    if recursion > 0 and not os.path.isdir(subprojectPath):
        return

    hasDebianDir = os.path.exists(os.path.join(subprojectPath, 'debian'))
    hasGitDir = os.path.exists(os.path.join(subprojectPath, '.git'))

    # Iterate sub-directories if debian directory doesn't exists
    if not hasDebianDir and hasGitDir:
        os.chdir(subproject)
        for file in os.listdir(subprojectPath):
            subproject = os.fsdecode(file)
            buildProject(subproject, subprojectPath, recursion + 1)
        os.chdir("..")
        return

    print("")
    print("   #######################################################################")
    print("   ### Downloading build dependencies for %s" % subproject)
    print("   #######################################################################")
    print("")
    os.system("apt build-dep %s" % subproject)
    print("")

    # Don't attempt to git clone if we're iterating inside a sub-directory
    if recursion == 0:
        removeProject(subproject)
        cloneProject(subproject)

    os.chdir(subproject)

    print("")
    print("   #######################################################################")
    print("   ### Building %s" % subproject)
    print("   #######################################################################")
    print("")
    os.system("dpkg-buildpackage -us -uc -j%d" % threads)
    print("")
    print("   #######################################################################")
    print("   ### Installing %s" % subproject)
    print("   #######################################################################")
    print("")
    os.system("sudo dpkg -i ../*.deb")
    print("")
    print("   #######################################################################")
    print("   ### Cleaning up")
    print("   #######################################################################")
    print("")

    if hasGitDir:
        os.system("git clean -df .")
        os.system("git reset --hard")

    os.chdir("..")
    os.system("rm -f *_*")

for subproject in selected_project.subprojects:
    buildProject(subproject, root)
