#!/usr/bin/python3
#

import os
import shutil
import subprocess
import sys


class bcolors:
    HEADER = '\033[95m'
    OKBLUE = '\033[94m'
    OKCYAN = '\033[96m'
    OKGREEN = '\033[92m'
    WARNING = '\033[93m'
    FAIL = '\033[91m'
    ENDC = '\033[0m'
    BOLD = '\033[1m'
    UNDERLINE = '\033[4m'


def proceed(ask="Proceed?"):
    while True:
        uf = input("\n%s [Y/n/q]" % ask)
        if len(uf) == 0:
            uf = "y"
        if uf.lower() in ["y", "n", "q"]:
            break
    if uf == "q":
        sys.exit(1)
    else:
        return uf.lower() == "y"


def delete_destination():
    return proceed("/!\\ Delete Destination including ALL files? /!\\")


def failed(error_msg):
    print("    " + bcolors.WARNING + error_msg.rstrip("\n") + bcolors.ENDC)
    print("    [" + bcolors.FAIL + " FAILED  " + bcolors.ENDC + "]")


def success():
    print("    [" + bcolors.OKGREEN + " SUCCESS " + bcolors.ENDC + "]")


BASE_GIT_URL = "https://git.mount-mockery.de/dirk"
REPOS = (
    (BASE_GIT_URL + "/" + "bin.git", "~/bin"),
    (BASE_GIT_URL + "/" + "bash.git", "~/.bash"),
    (BASE_GIT_URL + "/" + "config_files.git", "~/.config_files"),
)
print("Cloning the following repositories:")
for data in REPOS:
    print("    %s --> %s" % data)
if proceed():
    for url, target in REPOS:
        command = "git clone %s %s" % (url, target)
        print("Cloning %s" % url)
        process = subprocess.Popen(command, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
        process.wait()
        if process.returncode == 0:
            success()
        else:
            failed(process.stderr.read().decode("utf-8"))

CONFIG_COMMANDS = (
    "GS=`grep .bash/enabled ~/.bashrc`; [ ${#GS} -ne 0 ] || cat ~/.bash/BASHRC_ADDON >> ~/.bashrc",
    "mkdir -p ~/.cache/vim && mkdir -p ~/.vim && ln -s ~/.config_files/vimrc ~/.vimrc && ln -s ~/.config_files/vim_skeletons ~/.vim/skeletons",
    "which tmux && ln -s ~/.config_files/tmux.conf ~/.tmux.conf",
    "mkdir -p ~/.config && ln -s ~/.config_files/powerline_gitstatus ~/.config/powerline",
    "mkdir -p ~/.ssh && chmod 700 ~/.ssh && ln -s ~/.config_files/ssh_config ~/.ssh/config",
)
print("\n\n\nAdding the configuration to your environment:")
for command in CONFIG_COMMANDS:
    print("   ", command)
if proceed():
    for command in CONFIG_COMMANDS:
        print("Executing %s" % command)
        process = subprocess.Popen(command, shell=True, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
        process.wait()
        if process.returncode == 0:
            success()
        else:
            failed(process.stderr.read().decode("utf-8"))

DATA_LINKS = (
    ('~/data', 'prj'),
    ('~/data', 'prj/Arduino'),
    ('~/data', 'Schreibtisch'),
    ('/usr/data/dirk/local', 'C64'),
    ('/usr/data/dirk/local', 'Downloads'),
    ('/usr/data/dirk/local', 'media_images'),
    ('/usr/data/dirk/local', 'Videos'),
)
print("\n\n\nAdding the ~/data softlinks to your home directory")
for src_path, path in DATA_LINKS:
    print("    %s -> %s" % (os.path.join(src_path, path), os.path.join('~', os.path.basename(path))))
if proceed():
    delete_dest = delete_destination()
    for src_path, path in DATA_LINKS:
        src = os.path.expanduser(os.path.join(src_path, path))
        dest = os.path.expanduser(os.path.join("~", os.path.basename(path)))
        print("    Creating symlink: %s -> %s" % (src, dest))
        # Check existance of dest
        if not os.path.exists(src):
            failed("Source %s does not exists." % src)
            continue
        if os.path.exists(dest):
            if delete_dest:
                try:
                    os.remove(dest)
                except IsADirectoryError:
                    shutil.rmtree(dest)
            else:
                failed("Destination %s already exists." % dest)
                continue
        # Create Symbolic Link
        os.symlink(src, dest)
        success()