#!/usr/bin/env python3

import os
import subprocess
import shutil
import sys

TOOLCHAINS = {
    'windows': 'x86_64-w64-mingw32'
}

TARGET_OS = os.environ.get('GOOS', '')
VALID_TARGETS = TOOLCHAINS.keys()
if TARGET_OS not in VALID_TARGETS:
    sys.exit(f'{TARGET_OS} is not in supported targets: {",".join(VALID_TARGETS)}')

TOOLCHAIN = TOOLCHAINS[TARGET_OS]

'''
Format:

Git Dependency:
name: <dependency_name>
url: <repository_url>
version: <git_tag>
protocol: 'git'
cmd: <command_how_to_install>

HTTP Dependency:
name: <dependency_name>
url: <http_url>
extension: <file_extension_that_will_be_downloaded>
protocol: 'http'
cmd: <command_how_to_install>
'''
DEPENDENCIES = []
ROOT_DIR = '/tmp'


def log(name, description):
    print(f'{name}: {description}')


def run_cmd(command):
    p = subprocess.run(command, shell=True, capture_output=True)

    # If a command fails, exit with the return code with the error message.
    if p.returncode != 0:
        sys.exit(p.stderr.decode('utf-8'))

    return p


def pull_from_git(dependency):
    name = dependency['name']
    url = dependency['url']
    version = dependency['version']

    run_cmd(f'git clone --branch={version} --depth=1 {url} {name}')
    install(dependency)


def pull_from_http(dependency):
    name = dependency['name']
    url = dependency['url']
    extension = dependency['extension']
    tar_name = f'{name}.{extension}'

    run_cmd(f'curl -L {url} > {tar_name}')
    shutil.unpack_archive(tar_name, name)

    extracted = os.listdir(name)

    # If it's being wrapped with another folder, we move them
    # one level higher so that we have all the source codes in the root
    if len(extracted) == 1:
        pwd = os.getcwd()
        package_folder = os.path.join(pwd, name)
        wrapper_folder = os.path.join(package_folder, extracted[0])
        if os.path.isdir(wrapper_folder):
            for to_move in os.listdir(wrapper_folder):
                src = os.path.join(name, wrapper_folder, to_move)
                dst = os.path.join(package_folder, to_move)
                shutil.move(src, dst)

    install(dependency)


def pull(dependency):
    protocol = dependency['protocol']
    name = dependency['name']
    handlers = {
        'http': pull_from_http,
        'git': pull_from_git,
    }

    log(name, f'pulling with {protocol} protocol')
    return handlers[protocol](dependency)


def install(dependency):
    name = dependency['name']
    cmd = dependency['cmd']

    log(name, f'installing')
    os.chdir(os.path.join(ROOT_DIR, name))
    run_cmd(cmd)


os.chdir(ROOT_DIR)
for dependency in DEPENDENCIES:
    pull(dependency)

print()
print('installed dependencies:')
p = run_cmd('pkg-config --list-all')
print(p.stdout.decode('utf-8'))
