#!/usr/bin/env python3

import subprocess
import glob
import logging
import sys
import os

vlp_version = "v2124"
yocto_recipe_name = "rzg_bsp_***_"+vlp_version+".tar.gz"
oss_pkg_name = "oss_pkg_"+vlp_version+".7z"
yocto_recipe_name_gecko = "rzg_bsp_gecko_"+vlp_version+".tar.gz"
oss_pkg_name_gecko = "oss_pkg_gecko_"+vlp_version+".7z"
yocto_recipe_eva = glob.glob("./rzg_bsp_eva_"+vlp_version+".tar.gz")
yocto_recipe_pro = glob.glob("./rzg_bsp_pro_"+vlp_version+".tar.gz")
yocto_recipe_gecko = glob.glob("./rzg_bsp_gecko_"+vlp_version+".tar.gz")
oss_pkg = glob.glob("./oss_pkg_"+vlp_version+".7z")
oss_pkg_gecko = glob.glob("./oss_pkg_gecko_"+vlp_version+".7z")
target_board = chosen_gui = qt_demo_use = pkg_apt = None
work_path = os.getcwd()
chips = {"1": "h", "2": "m", "3": "n", "4": "e", "5": "c"}
board = {"1": "iwg21m", "2": "iwg20m-g1m", "3": "iwg20m-g1n",
         "4": "iwg22m", "5": "iwg23s"}
gui = {"1": "/qt", "2": "/gecko", "3": ""}
pkg = "gawk wget git-core diffstat unzip texinfo gcc-multilib "\
      "build-essential chrpath socat cpio python python3 python3-pip "\
      "python3-pexpect xz-utils debianutils iputils-ping libsdl1.2-dev "\
      "xterm p7zip-full "
pkg_for_html = "autoconf2.13 clang llvm clang-3.9 llvm-3.9"
log_name = vlp_version+"_script.log"

logger = logging.getLogger('LoggingTest')
logger.setLevel(logging.DEBUG)
file_handler = logging.FileHandler(log_name)
logger.addHandler(file_handler)
stream_handler = logging.StreamHandler(sys.stdout)
logger.addHandler(stream_handler)

def check_user_environment():
    global yocto_recipe, target_board, chosen_gui, qt_demo_use

    if yocto_recipe_eva != [] and yocto_recipe_pro != []:
        yocto_recipe = yocto_recipe_pro
    elif yocto_recipe_eva != []:
        yocto_recipe = yocto_recipe_eva
    elif yocto_recipe_pro != []:
        yocto_recipe = yocto_recipe_pro
    elif yocto_recipe_eva == [] and yocto_recipe_pro == []:
        yocto_recipe = []

    if yocto_recipe == [] or oss_pkg == []:
        print("\n\nERROR: There are no Yocto recipe package"
              "("+yocto_recipe_name+") or Open Source "
              "packages("+oss_pkg_name+") in your working directory.")
        print("Please copy the files to the directory "
              "and try again to run this script.\n\n")
        sys.exit(None)

    print("\nWhat is your target board?")
    print("Please enter one of the following numbers "
          "corresponding to the target board.")
    print("[1] RZ/G1H, [2] RZ/G1M, [3] RZ/G1N, [4] RZ/G1E, [5] RZ/G1C")
    while target_board not in chips:
        target_board = input("\nPlease Enter Number: ")

    print("\nWhich GUI framework do you want to use?")
    print("Please enter one of the following numbers "
          "corresponding to the framework.")
    print("[1] Qt, [2] HTML5, [3] None* (*Does not use Qt and HTML5.)")
    while chosen_gui not in ["1", "2", "3"]:
        chosen_gui = input("\nPlease Enter Number: ")
        if chosen_gui == "1":
            while qt_demo_use != "y" and qt_demo_use != "n":
                qt_demo_use = input("\nDo you want to include "
                                    "Qt HMI demo applications? (y/n): ")

    if chosen_gui == "2":
        if yocto_recipe_gecko == [] or oss_pkg_gecko == []:
            print("\n\nERROR: There are no Yocto recipe package"
                  "("+yocto_recipe_name_gecko+") or Open Source "
                  "packages("+oss_pkg_name_gecko+") in your working "
                  "directory.")
            print("Please copy the files to the directory "
                  "and try again to run this script.\n\n")
            sys.exit(None)

    var_list = [chips[target_board], board[target_board],
                target_board, chosen_gui, qt_demo_use]
    logger.debug("Variables: chips={0[0]}, board={0[1]}, "
                 "target_board={0[2]}, chosen_gui={0[3]}, "
                 "qt_app_use={0[4]}".format(var_list))
    return


cmd_common = cmd_qt_demo = cmd_html = []


def command_all():
    global cmd_common, cmd_qt_demo, cmd_html, cmd_patch

    cmd_common = [
        "cat /etc/issue",
        "df -h /home",
        "mkdir -v ./user_work",
        "tar xvzf "+str(yocto_recipe[0])+" -C ./user_work",
        "cd ./user_work/meta-renesas/meta-rzg1 ; "
        "./copy_mm_software_lcb.sh ../../MMP",
        "cd ./user_work/meta-renesas/meta-rzg1 ; "
        "./copy_gfx_software_rzg1{}.sh ../../MMP".format(chips[target_board]),
        "cd ./user_work/poky ; set `pwd`/../build ; . ./oe-init-build-env",
        "cd ./user_work/build/conf ; cp ../../meta-renesas/meta-rzg1/templates"
        "/{0}{1}/*.conf ./".format(board[target_board], gui[chosen_gui]),
        "7z x -o./user_work/build/ ./oss_pkg_"+vlp_version+".7z"
        ]

    cmd_qt_demo = "cd ./user_work/build/conf ; cp ../../meta-rzg-demos/"\
                  "meta-rzg1/qt-hmi-demo/template/"\
                  "{}/*.conf ./".format(board[target_board])

    if chosen_gui == "2":
        cmd_html = [
            "tar xvzf "+str(yocto_recipe_gecko[0])+" -C ./user_work",
            "7z x -o./user_work/build/ ./oss_pkg_gecko_"+vlp_version+".7z"
            ]
        cmd_patch = [
            "cd ./user_work/meta-renesas ; patch -p1 < ../extra/"
            "0001-mmngr-iwg22m-iwg23s-reducing-CMA-reserved-for-MMP-to.patch"
            ]
    return


def cmd_exe(cmd):
    proc = subprocess.run(cmd, shell=True, stdout=subprocess.PIPE,
                          stderr=subprocess.STDOUT)
    logger.debug('Command = "{}"   is executed.'.format(cmd))
    logger.debug(proc.stdout.decode("utf8"))
    return proc.returncode


def cmd_exe_checkresult(cmd):
    x = cmd_exe(cmd)
    if x != 0:
        logger.debug("\n\nERROR: Command = ["+cmd+"] failed.")
        print("This script will stop. \n\n")
        sys.exit(None)
    x = 1
    return


def check_network(network):
    while True:
        y = cmd_exe(network)
        if y == 0:
            break
        logger.debug("\n\nWARRNING: Linux Host PC is not"
                     " connected to the network.")
        print("Please connect to the network.")
        print("Process wait until it is online.")
        print(input("\nWill you try again? "
                    "(Yes: [enter], No: [Ctrl + C]):"))
    return


def apt_exe(package):
    global pkg_apt
    check_network("sudo apt-get update")
    z = cmd_exe("dpkg -l "+package)
    if z != 0:
        print("\n\nIt is necesarry to install the following"
              " packages to your Linux Host PC.\nPackages = ["+package+"]")
        while pkg_apt != "n" and pkg_apt != "y":
            pkg_apt = input("\nIs it OK to install the packages?(y/n):")
            if pkg_apt == "y":
                cmd_exe_checkresult("sudo apt-get install "+package)
            elif pkg_apt == "n":
                print("\n\n**   The build sequence was interrupted.  **\n\n")
                sys.exit(None)
    return


def setup_build_env():
    if chosen_gui != "2":
        apt_exe(pkg)
    elif chosen_gui == "2":
        apt_exe(pkg+pkg_for_html)

    for s in cmd_common:
        cmd_exe_checkresult(s)

    if chosen_gui == "1" and qt_demo_use == "y":
        cmd_exe_checkresult(cmd_qt_demo)
    elif chosen_gui == "1" and qt_demo_use == "n":
        pass
    elif chosen_gui == "2":
        for t in cmd_html:
            cmd_exe_checkresult(t)
        if target_board in ["4", "5"]:
            cmd_exe_checkresult(cmd_patch)
    return


def finish():
    print("\n\n**  The sequence of this script was successfully"
          " completed.  **\n**  Please refer to the manual and "
          "execute the next procedures.  **\n")
    return


if __name__ == "__main__":
    check_user_environment()
    command_all()
    setup_build_env()
    finish()
