#!/usr/bin/env python3

import argparse, sys, shutil, os, subprocess

sys.path.append(os.path.dirname(__file__) + '/lib')

import tamarin

def create_args_parser():
    '''Return a new configured ArgumentParser'''
    profile_names = tamarin.get_available_profile_names()

    parser = argparse.ArgumentParser(description="Generate packages for various GNU/Linux distributions")

    # Define available/required arguments and flags
    parser.add_argument("project_directory", help="The path to your project to package")
    parser.add_argument("-o", "--output", help="The path to the generated packages destination directory", default=".")
    parser.add_argument("-p", "--profile", help="The profile to use to package this project (default: debian)", choices=profile_names, default='debian')
    parser.add_argument("-a", "--architecture", help="The target architecture for the package (default: amd64)", default='amd64')
    parser.add_argument("-b", "--base", help="Use the specified image instead of the profile's one", default='')
    parser.add_argument("--rebuild", help="Ignore cache and rebuild container's image", action="store_true", default=False)
    parser.add_argument("--debug", help="Will add extra output and start the container in interactive mode", action="store_true", default=False)
    parser.add_argument("--cleanup", help="Clear the workspace and remove obsolete Docker images before build", action="store_true", default=False)
    parser.add_argument("--override-docker-args", help="Override all 'docker run' arguments. Use '[IMAGE_TAG]', '[PROFILE]' and '[ARCH]' to insert the corresponding values into your command.", default="")

    return parser

def build_image(build_workspace, base_image, profile_name, profile, debug=False, rebuild=False):

    with open("{:s}/Dockerfile".format(build_workspace), 'w') as dockerfile:
        dockerfile.write("FROM {:s}\n".format(base_image))

    # Configure "containerbuild" hooks environment
    hooks_env = os.environ.copy()
    hooks_env["PATH"] = os.environ['PATH'] + ':' + tamarin.get_lib_dir()

    # Run hooks
    tamarin.run_profile_hooks(profile, 'containerbuild', cwd=build_workspace, env=hooks_env, debug=debug)

    image_tag = "tamarin:{:s}_{:s}_{:d}".format(profile_name, base_image.replace(':', '_'), os.getpid())

    build_args = [ "build", "-t", image_tag ]

    if rebuild:
        build_args += [ "--no-cache" ]

    tamarin.run_docker(build_args + [build_workspace], debug=debug)

    return image_tag

def cleanup(build_workspace=None, debug=False):

    if build_workspace == None:
        build_workspace = tamarin.get_workspace_subdir('tmp')

    # Suppression de l'espace de travail de build
    shutil.rmtree(build_workspace, ignore_errors=True)

def validate_args(args):
    '''TODO'''

if __name__ == "__main__":

    parser = create_args_parser()
    args = parser.parse_args()

    if args.cleanup:
        cleanup(debug=args.debug)

    # Verify project directory
    project_dir = os.path.abspath(args.project_directory)
    output_dir = os.path.abspath(args.output)

    # Load build profile
    profile = tamarin.load_profile(args.profile, debug=args.debug)

    workspace = tamarin.get_workspace_dir()

    pid = os.getpid()
    build_workspace = tamarin.get_workspace_subdir('tmp/build_{:d}'.format(pid))

    base_image = args.base if args.base != '' else profile['profile']['default_image']

    image_tag = build_image(build_workspace, base_image, args.profile, profile,  debug=args.debug, rebuild=args.rebuild)

    kwargs = dict()
    kwargs['debug'] = args.debug

    docker_args = []

    # Append custom arguments
    if args.override_docker_args != "":
        docker_args = args.override_docker_args.replace('[IMAGE_TAG]', image_tag)
        docker_args = docker_args.replace('[PROFILE]', args.profile)
        docker_args = docker_args.replace('[ARCH]', args.architecture)
    else:

        docker_args += [ "run", "--rm" ]

        # volumes definition
        docker_args += [
            "-v", "{:s}:/src:ro".format(project_dir),
            "-v", "{:s}:/dist".format(output_dir),
            "-v", "{:s}:/tamarin/hooks:ro".format(tamarin.get_hooks_dir()),
            "-v", "{:s}:/tamarin/lib:ro".format(tamarin.get_lib_dir()),
            "-v", "{:s}:/tamarin/profiles:ro".format(tamarin.get_profiles_dir())
        ]

        # Use environment proxy if defined
        for proxy_var in ['HTTP_PROXY', 'HTTPS_PROXY', 'http_proxy', 'https_proxy']:
            if proxy_var in os.environ:
                docker_args += ["-e", "{:s}={:s}".format(proxy_var, os.environ[proxy_var])]

        if args.debug:
            kwargs['pty'] = True
            docker_args += ["-it", image_tag, "/bin/sh"]
            helper_cmd = " ".join(["/usr/bin/python3", "/tamarin/lib/build.py", args.profile, args.architecture])
            print("Executer '{:s}' pour lancer la construction du paquet.".format(helper_cmd))
        else:
            docker_args += [image_tag, "/usr/bin/python3", "/tamarin/lib/build.py", args.profile, args.architecture]

    # Start container
    tamarin.run_docker(docker_args, **kwargs)

    cleanup(build_workspace, debug=args.debug)