#!/usr/bin/python3

import argparse
import os
import shutil
import sys
import typing

from waf_wrapper_lib import install_log

PROGRAM_NAME = 'waf-wrapper'
PROGRAM_DESCRIPTION = 'A WAF wrapper intercepting an install command to fill in the install log'
DEFAULT_INSTALL_LOG_FILE_NAME = 'wafInstall.log'


def _format_default_log_path() -> str:
    introot_path = os.getenv('PREFIX')
    if introot_path is None:
        introot_path = os.getenv('INTROOT')
        if introot_path is None:
            home_path = os.getenv('HOME')
            introot_path = home_path + '/INTROOT'

    return os.path.join(introot_path, DEFAULT_INSTALL_LOG_FILE_NAME)


def _parse_args() -> typing.Tuple[argparse.Namespace, list]:
    parser = argparse.ArgumentParser(
        prog=PROGRAM_NAME,
        description=PROGRAM_DESCRIPTION)

    parser.add_argument(
        "--disable-install-log",
        dest="disable_installation_log",
        default=False,
        action="store_true",
        help=(
            "Disables the post-installation action to update the installation log."
        ),
    )

    parser.add_argument(
        "--install-log-path",
        dest="installation_log_path",
        default=_format_default_log_path(),
        action="store",
        type=str,
        help=(
            "Specifies the default location of the installation log."
        ),
    )

    parser.add_argument(
        "-hh",
        dest="print_waf_help",
        action="store_true",
        help=(
            "Displays the help message of WAF."
        ),
    )

    return parser.parse_known_args()


def _handle_install_log(args : argparse.Namespace, waf_args : list) -> None:
    if "install" in waf_args:
        install_log.append_entry(args, waf_args)


def _invoke_waf(waf_args : list) -> int:
    system_retval = os.system(shutil.which('waf') + ' ' + ' '.join(waf_args))
    return os.waitstatus_to_exitcode(system_retval)


def main() -> int:
    args, waf_args = _parse_args()
    if args.print_waf_help:
        return _invoke_waf(['-h'])
    # Runs the waf command
    result = _invoke_waf(waf_args)
    # Writes in the install log only is the waf command succeded (and includes install)
    if not result:
       _handle_install_log(args, waf_args)
    return result


if __name__ == """__main__""":
    result = main()
    sys.exit(result)
