#! /usr/bin/env python
import sys
import os
import subprocess
import datetime
################################################################################
# Compile script for Manyo-lib release version
#    ver 2023/7/11
#    written by Y. Inamura
#########################################################################
man_script = "Usage :     {:s} <command> [options]\n".format(sys.argv[0])
man_script += """
       command: [depend/man/make/install/clean]
       options: --debug --help --prefix --py-prefix
                --other-modules --numth --pyver
                --rev --without-depend --with-para --without-para
  -------------------------------------------------------
  depend    : depend script
  man       : script to make manual
  make      : make
  install   : make install
  uninstall : make uninstall
  clean     : make clean

  --debug          : debug mode
  --help           : show this help

  --prefix=/hoge/hogege/hoge
                   : set MLFSOFT_PATH,
                     the root path including manyo-lib and python-utsusemi folders
  --py-prefix=/hoge/hogege/hoge
                   : set PYUTSUPREFIX, default ${MLFSOFT_PATH}/python-utsusemi
  --dist-name=Ubuntu
                   : Linux distribution name [RH6,RH7,Ubuntu]
  --other-modules=SAS,DNA
                   : required other modules if need(default Utsusemi)

  --numth=n        : set the number of multi-threading
  --pyver=n.m      : set python version
                     If not set pyver, the version of python executing this is used
  --rev=nnnn       : set revision number if need
  --without-depend : does not run depend script
  --with-para      : use compile option of -j (default is no-use of -j)
  --without-para   : not use compile option of -j

"""

#########################################################################
#   CXX            : compiler
#   PYVER          : version of python
#   NUM_OF_THREADS : number of threading
#   MANYO_PATH     : path to  manyo-core installed
#   INSTALL_PATH   : path to install
#   OTHER_MANYO_PAC: Other Manyo Package names required by compile
#   ENV_FILE_NAME  : file name of shell script to set Manyo environment
#   EXT_LIB_ROOT   : root path to external library required by Manyo-lib
#########################################################################
CXX = "g++"
PYVER = ""
try:
    PYVER = "{:d}.{:d}".format(sys.version_info.major, sys.version_info.minor)
except:
    pass
NUM_OF_THREADS = 8
MLFSOFT_PATH = "/opt/mlfsoft"
MANYO_PATH = MLFSOFT_PATH + "/manyo"
PYUTSU_PREFIX = ""
INSTALL_PATH = MANYO_PATH
OTHER_MANYO_PAC = ["Utsusemi"]
ENV_FILE_NAME = "bashrc.template"
EXT_LIB_ROOT = "/usr/local"
DIST_NAME = ""
if os.path.exists("/etc/redhat-release"):
    f = open("/etc/redhat-release", "r")
    r = f.readline()
    f.close()
    r_list = r.split(" ")
    for i, rel in enumerate(r_list):
        if rel == "release":
            p = r_list[i + 1]
            break
    if p.find("7") == 0 or p.find("8") == 0:
        DIST_NAME = "RH7"
    else:
        DIST_NAME = "RH6"
elif os.path.exists("/etc/os-release"):
    DIST_NAME = "Ubuntu"
else:
    pass

isDebug = False
isWithDepend = True
isCompPara = False
isNotManyoCore = True
utsusemi_rev = 0
isPlacedUgao = False

if "UTSUSEMI_REV" in os.environ:
    utsusemi_rev = int(os.environ["UTSUSEMI_REV"])
else:
    try:
        cp = subprocess.run("git log -1 --date=short|grep 'Date:'", shell=True, capture_output=True, encoding="utf-8")
        if cp.stderr == '':
            latest_date_git = cp.stdout.split()[1]
            latest_date_v = latest_date_git.split("-")
            utsusemi_rev = latest_date_v[0][-2:] + latest_date_v[1] + latest_date_v[2]
    except:
        pass

#############################################
# Check arguments
#############################################

do_command = ""

# print(sys.argv[2:])
unidentified_args = []
if (len(sys.argv) > 1):
    used_args = sys.argv[1:]
    num_of_args = len(used_args)
    ind = 0
    while(True):
        if ind == num_of_args:
            break
        an_arg = used_args[ind]
        ind += 1

        if an_arg in ["depend", "make", "install", "uninstall", "clean", "man"]:
            do_command = an_arg
        elif an_arg == "--debug":
            isDebug = True
        elif an_arg == "--without-depend":
            isWithDepend = False
        elif an_arg == "--without-para":
            isCompPara = False
        elif an_arg == "--with-para":
            isCompPara = True
        elif an_arg.find("--rev=") == 0:
            utsusemi_rev = int(an_arg[6:])
            print("utsusemi_rev = {:s}".format(utsusemi_rev))
        elif an_arg.find("--pyver=") == 0:
            PYVER = an_arg[8:].strip()
            print("PYVER= {}".format(PYVER))
        elif an_arg.find("--numth=") == 0:
            NUM_OF_THREADS = int(an_arg[8:])
            print("NUM_OF_THREADS= {:d}".format(NUM_OF_THREADS))
        elif an_arg.find("--prefix=") == 0:
            MLFSOFT_PATH = an_arg[9:]
            MANYO_PATH = MLFSOFT_PATH + "/manyo"
            INSTALL_PATH = MANYO_PATH
            print("MANYO_PATH= {}".format(MANYO_PATH))
            print("INSTALL_PATH= {}".format(INSTALL_PATH))
        elif an_arg.find("--py-prefix=") == 0:
            PYUTSU_PREFIX = an_arg[12:]
            print("PYUTSU_PREFIX = {}".format(PYUTSU_PREFIX))
        elif an_arg.find("--other-modules=") == 0:
            mod_arg = an_arg[16:]
            OTHER_MANYO_PAC = mod_arg.split(",")
            for a_mod in OTHER_MANYO_PAC:
                print("OTHER_MANYO_PAC= {}".format(a_mod))
        elif an_arg.find("--help") == 0:
            do_command = ""
            break
        elif an_arg.find("--dist-name=") == 0:
            DIST_NAME = an_arg[12:]
            if not (DIST_NAME in ["RH6", "RH7", "Ubuntu", "Ubuntu16", "Ubuntu18", "Ubuntu20"]):
                print(" ERROR : --dist-name is invalid")
                sys.exit(-1)
        else:
            print("Unindentify argument = {}".format(an_arg))
            unidentified_args.append(an_arg)

if (do_command == "") or len(unidentified_args) != 0:
    print(man_script)
    sys.exit(0)

if (do_command == "clean") or (do_command == "uninstall"):
    isWithDepend = False

if (do_command == "make"):
    do_command = ""

if os.path.exists(os.path.join(os.getcwd(), "core")):
    isNotManyoCore = False

#############################################
# Check compile target ( manyo-core or not )
#############################################
if isNotManyoCore:
    PACKAGE_NAME = ""
    makefilepath = os.path.join(os.getcwd(), "manyo", "Makefile")
    if os.path.exists(makefilepath):
        fo = open(makefilepath, "r")
        ll = fo.readlines()
        fo.close()
        for aline in ll:
            print(aline)
            if aline.find("PACKAGE_NAME") != -1:
                PACKAGE_NAME = aline.split("=")[1].strip()
                break
    if PACKAGE_NAME == "":
        print("Makefile is invalid. (No PACKAGE_NAME)")
        sys.exit(1)

if DIST_NAME == "Ubuntu":
    try:
        fo = open("/etc/issue", "r")
        t = fo.readline()
        fo.close()
        v = t.split(' ')
        if v[1].find("22.04") == 0 or v[1].find("20.04") == 0 or v[1].find("19.") == 0:
            DIST_NAME = "Ubuntu20"
        elif v[1].find("18.04") == 0 or v[1].find("17.") == 0 or v[1].find("16.04") == 0 or v[1].find("15.") == 0:
            DIST_NAME = "Ubuntu16"
    except:
        print(" ERROR : failed to distinguish version of Ubuntu")
        sys.exit(-1)
elif DIST_NAME == "Ubuntu18":
    DIST_NAME = "Ubuntu16"


#########################################################################
# execute make or make install
#############################################
OTHER_MAN_PAC = ["Manyo", "MLF"]
for pac in OTHER_MANYO_PAC:
    OTHER_MAN_PAC.append(pac)

EXT_LIB_PATH = os.path.join(EXT_LIB_ROOT, "lib")
EXT_INC_PATH = os.path.join(EXT_LIB_ROOT, "include")

com = "export MANYO_PATH={:s};".format(MANYO_PATH)
if isNotManyoCore:
    com += "export INSTALL_PATH={:s};".format(INSTALL_PATH)
    com += "export LIBRARY_PATH=${MANYO_PATH}/lib:${INSTALL_PATH}:"
    com += "{:s};".format(EXT_LIB_PATH)
else:
    com += "export LIBRARY_PATH=${MANYO_PATH}/lib:"
    com += "{:s};".format(EXT_LIB_PATH)
com += "export LD_LIBRARY_PATH=${LIBRARY_PATH};"
if PYVER != "":
    if DIST_NAME.find("Ubuntu20") == 0:
        com += "export C_INCLUDE_PATH=/usr/include/nexus:/usr/include/hdf5/serial:${MANYO_PATH}/include:"
        com += "/usr/include/python{:s}:{:s}".format(PYVER, EXT_INC_PATH)  # [inamura 201103 for Ubuntu 20.04]
    elif DIST_NAME.find("Ubuntu16") == 0:  # for Ubuntu 16 or 18
        com += "export C_INCLUDE_PATH=/usr/include/hdf5/serial:${MANYO_PATH}/include:"
        com += "/usr/include/python{:s}:{:s}".format(PYVER, EXT_INC_PATH)  # [inamura 201103 for Ubuntu 16.04 and Ubuntu 18.04]
    else:
        com += "export C_INCLUDE_PATH=${MANYO_PATH}/include:"
        com += "{:s}".format(EXT_INC_PATH)
else:
    com += "export C_INCLUDE_PATH=/usr/include/hdf5/serial:${MANYO_PATH}/include:"
    com += "{:s}".format(EXT_INC_PATH)
for m_pac_name in OTHER_MAN_PAC:
    com += ":${MANYO_PATH}/include/"
    com += "{:s}".format(m_pac_name)
com += "; "
com += 'export INC_EXT="'
for m_pac_name in OTHER_MAN_PAC:
    com += "{:s} ".format(m_pac_name)
com += '"; '
com += "export CPLUS_INCLUDE_PATH=${C_INCLUDE_PATH};"
com += "export PYTHONPATH=${MANYO_PATH};"
com += "export PATH=${MANYO_PATH}/bin:${PATH};"
if isNotManyoCore and isWithDepend:
    com += "cd manyo;./depend;cd ..;"

if (do_command != "depend"):
    com += 'make {:s} '.format(do_command)
    if isCompPara:
        com += '-j '
    if DIST_NAME == "":
        DIST_NAME = "Ubuntu"
    com += ' DIST_NAME={:s}'.format(DIST_NAME)
    if PYVER != "":
        com += ' CXX={:s} PyVer={:s} NUM_MULTH={:d}'.format(CXX, PYVER, NUM_OF_THREADS)
    else:
        com += ' CXX={:s} NUM_MULTH={:d}'.format(CXX, NUM_OF_THREADS)
    com += ' UTSUSEMI_REV={}'.format(utsusemi_rev)
    if PYUTSU_PREFIX != "":
        com += ' PYUTSUPREFIX={}'.format(PYUTSU_PREFIX)
    if isPlacedUgao:
        pass
    else:
        com += ' WITOUTUGAO=T'

print("command = {}".format(com))
if isDebug:
    pass
else:
    retcode = os.system(com)
    if retcode:
        sys.stderr.write("Return code '{}', is not 0.\n".format(retcode))
        raise RuntimeError("Error has been caused in building.")


#########################################################################
# make environ file
#############################################
env_temp = """# Utsusemi software environment 
# ({DATE1})

# Utsusemi Environment
export UTSUSEMI_INST_CODE=SIK
export UTSUSEMI_DATA_DIR=/data
export UTSUSEMI_USR_DIR=${{UTSUSEMI_USR_DIR-${{HOME}}}}
export UTSUSEMI_LOG_QUIET=n
export UTSUSEMI_MULTH=2
export UTSUSEMI_DEBUGMODE=n
#export UTSUSEMI_DEFAULT_FONTSIZE=14

# Path to MLF Software
MLFSOFT_PATH={MLFSOFT_PATH}

# Path to Manyo-lib
export MANYO_PATH=${{MLFSOFT_PATH}}/manyo

# PythonPath to utsusemi
PYUTSUSEMI_PATH={PYUTSU_PREFIX}

# External Library path
UTSUSEMI_EXT_LIBRARY_PATH=/usr/local/lib

# Utsusemi Environment
export UTSUSEMI_BASE_DIR=${{PYUTSUSEMI_PATH}}/utsusemi

# Python Path
PYTHONPATH=${{MANYO_PATH}}:${{PYUTSUSEMI_PATH}}:${{UTSUSEMI_BASE_DIR}}/facade
PYTHONPATH=${{UTSUSEMI_BASE_DIR}}/${{UTSUSEMI_INST_CODE}}/facade:${{UTSUSEMI_USR_DIR}}/facade:${{PYTHONPATH}}
export PYTHONPATH

# Shared Library Path
export LD_LIBRARY_PATH=${{MANYO_PATH}}/lib:${{UTSUSEMI_EXT_LIBRARY_PATH}}:${{LD_LIBRARY_PATH}}

# Executable path
export PATH=${{MANYO_PATH}}/bin:${{PATH}}

echo '==========================================='
echo ' Welcome to Utsusemi Environment for '${{UTSUSEMI_INST_CODE}}
echo '                             ver 4.0.{UTSUSEMI_REV}'
echo '==========================================='
"""


if PYUTSU_PREFIX == "":
    PYUTSU_PREFIX = MLFSOFT_PATH + "/python-utsusemi"

dt = datetime.datetime.today()
env_contents = env_temp.format(DATE1="{}/{}/{}".format(dt.year, dt.month, dt.day),
                               MLFSOFT_PATH=MLFSOFT_PATH, PYUTSU_PREFIX=PYUTSU_PREFIX,
                               UTSUSEMI_REV=utsusemi_rev)

if isDebug:
    print(env_contents)
else:
    fo = open(os.path.join(os.getcwd(), ENV_FILE_NAME), 'w')
    fo.write(env_contents)
    fo.close()
