"""Entry point module: get-system

This file should not be modified.
"""
import os

from diva_evaluation_cli.bin.private_src.implementation.utils.\
    actev_cli_environment import init_environment, export_variable

from diva_evaluation_cli.bin.private_src.implementation.get_system.\
    system_types_definition import system_types


def entry_point(url, system_type, location=None, user=None, password=None,
                token=None, install_cli=False, sha=None, name=False):
    """Private entry point.

    Downloads a credentialed, web-accessible content into src

    Args:
        url (str): Url to get the system
        location (str, optional): Path to store the system
        user (str, optional): Username to access the url
        password (str, optional): Password to access the url
        token (str, optional): Token to access the url
        install_cli (bool, optional): Information to know whether CLI has to be
            installed
        sha (str, optional): commit SHA or tag to checkout after cloning
        name (str, optional): Directory in which the system will be saved
    """
    try:
        command = system_types[system_type]()
        script = command.entry_point
    except KeyError:
        raise Exception("Unknown system type")

    # Init the actev_cli_environemnt variables
    init_environment()

    # Add variables into the actev_cli_environemnt
    export_variable('ACTEV_GET_SYSTEM_URL', url)

    # Destination of the software
    if not location:
        location = "None"

    # Username
    if user:
        export_variable('ACTEV_GET_SYSTEM_USER', user)
    else:
        user = "None"

    # Password
    if password:
        export_variable('ACTEV_GET_SYSTEM_PASSWORD', password)
    else:
        password = "None"

    # Token
    if token:
        export_variable('ACTEV_GET_SYSTEM_TOKEN', token)
    else:
        token = "None"

    # Whether installing the CLI
    if install_cli:
        install_cli = "True"
    else:
        install_cli = "False"

    # SHA
    if not sha:
        sha = "None"

    if not name:
        name = ""

    # go into the right directory to execute the script
    path = os.path.dirname(__file__)
    script = os.path.join(path, '../implementation/get_system/get/' + script)
    script += " " + url + \
              " " + location + \
              " " + user + \
              " " + password + \
              " " + token + \
              " " + install_cli + \
              " " + sha + \
              " " + name

    # status is a 16-bit long integer
    # The 8 strongest bits are exit_code
    # The 8 weakest bits are signal_number
    status = os.system(script)
    exit_code = status >> 8
    signal_number = status & (2**8 - 1)
    if status != 0:
        if signal_number == 2:  # SIGINT
            raise KeyboardInterrupt
        else:
            raise Exception("Error occured in %s (error code: %d)" % (
                command.entry_point, exit_code))
