#!/usr/bin/python3

import os
import subprocess
from gi.repository import GLib

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

USER_HOME = os.path.expanduser('~')
SETTINGS_PATH = "%s/mint-dev-tools" % GLib.get_user_config_dir()

settings = None
settings = GLib.KeyFile.new()

if os.path.exists(SETTINGS_PATH):
    settings.load_from_file(SETTINGS_PATH, GLib.KeyFileFlags.KEEP_COMMENTS)

print("")
print("Enter the name for your development directory - it will be placed in your home folder.")
print("")
dir_name = input("Name of folder (press return to name it 'Sandbox'):  ")
if dir_name == "":
    dir_name = "Sandbox"

## Create Sandbox
while not os.path.exists("%s/%s" % (USER_HOME, dir_name)):
    print("")
    print(" === CREATING A SANDBOX ===")
    os.system("mkdir -p ~/%s" % dir_name)
    print("Your sandbox was created in ~/%s. This is where you'll do all your development." % dir_name)

settings.set_string(GROUP, SANDBOX_PATH, "%s/%s" % (USER_HOME, dir_name))
settings.set_string(GROUP, SANDBOX_NAME, dir_name)

## Configure Git
while not os.path.exists("%s/.gitconfig" % USER_HOME):
    print("")
    print(" === CONFIGURING GIT ===")
    git_name = input('Enter your GIT username: ').strip()
    git_email = input('Enter your GIT email: ').strip()
    os.system("git config --global user.name \"%s\"" % git_name)
    os.system("git config --global user.email \"%s\"" % git_email)

## Configure SSH
choice = "0"
while choice not in ("", "1", "2"):
    print("")
    print("Configuring SSH. What do you want to do?")
    print("\t1) Create new SSH key pair (default)")
    print("\t2) Use an existing SSH key pair")
    choice = input("Select an option [1-2]: ")

if choice == "":
    choice = "1"
choice = int(choice)

pubkey_path = ""
if choice == 1:
    print("")
    print(" === CREATING AN SSH KEY (keep pressing enter for default choices) ===")
    print("     Please, create the key pair in your ~/.ssh folder")
    # Create ~/.ssh folder:
    os.makedirs("%s/.ssh" % USER_HOME, exist_ok=True)
    
    files_list_before = set(os.listdir("%s/.ssh" % USER_HOME))
    # Try to create key until success:
    os.system("ssh-keygen")
    files_list_after = set(os.listdir("%s/.ssh" % USER_HOME))

    # Sorted list of just created files:
    new_files = sorted(files_list_after - files_list_before)
    print(new_files)
    
    print("")
    if(len(new_files) != 2) or (new_files[1] != new_files[0] + '.pub'):
        print("Sorry, I couldn't automatically detect the file")
    else:
        pubkey_path = "%s/.ssh/%s" % (USER_HOME, new_files[1])

while not os.path.isfile(pubkey_path):
    default_path = ""
    if os.path.isfile("%s/.ssh/id_rsa.pub" % USER_HOME):
        default_path = "%s/.ssh/id_rsa.pub" % USER_HOME
    elif os.path.isdir("%s/.ssh" % USER_HOME):
        cur_files = os.listdir("%s/.ssh" % USER_HOME)
        cur_files = list(filter(lambda s: s.endswith('.pub'), cur_files))
        if len(cur_files) == 1:
            default_path = os.path.join(".ssh", cur_files[0])

    print("Please, enter your public key's path", end="")
    if default_path != "":
        print(" [%s]" % default_path, end="")
    print(": ", end="")

    pubkey_path = input()
    if pubkey_path == "":
        pubkey_path = default_path
    if pubkey_path != "":
        if not pubkey_path.endswith(".pub"):
            pubkey_path += ".pub"
        pubkey_path = os.path.join(USER_HOME, pubkey_path)

    if not os.path.isfile(pubkey_path):
        print("Error: path doesn't exist or not a file")

print("")
print("This is your public SSH key, you should now login to your Github account and add that key:")
print("")
os.system("cat %s" % pubkey_path)

print("")
print(" === REFRESHING APT CACHE ===")
print("")
input("Press ENTER to refresh the APT cache.")
os.system("sudo apt-get update")

max_threads = int(subprocess.getoutput("cat /proc/cpuinfo | grep processor | wc -l")) + 1

print("")
print("Enter the maximum number of threads to use for compiling.")
print("This has little effect on smaller projects, but can save a")
print("a lot of time when compiling Cinnamon.")
print("")
print("Maximum recommended for this system: %d" % max_threads)
print("")
print("Using less threads will ensure your system remains more responsive")
print("during compilation, at the cost of it potentially taking longer to complete.")
print("")
try:
    max_threads_user = int(input("Enter the number of threads to use, or press return to use the maximum: "))
except:
    max_threads_user = max_threads
print("")
print("Compiling with %d threads" % max_threads_user)

settings.set_integer(GROUP, THREADS, max_threads_user)

# We're all set, save the settings file which has our sandbox path
settings.save_to_file(SETTINGS_PATH)

print("")
print(" === ALL DONE ===")
print("")
print("Your environment is now set up. You can now use mint-dev-build to build projects.")
print("")
