#! /usr/bin/env python3
import sys
import os
import subprocess
import argparse
################################################################################
# Compile script for Manyo-lib release version
#    ver 20240710
#    written by Y. Inamura
#########################################################################
"""
Usage : python3 do_make_Utsusemi.py <command> [options]
       command: [depend/man/make/install/clean]
       options: --debug --help --manyo-path
                --other-modules --numth --pyver
                --rev --without-depend --with-para --without-para
  -------------------------------------------------------
  depend  : depend script
  man     : script to make manual
  make    : make
  install : make install
  clean   : make clean

  --help           : show this help

  --manyo-path=/hoge/hogege/hoge
                   : set MANYO_PATH

  --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

  --debug          : debug mode
"""

#########################################################################
#   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
MANYO_PATH = "/opt/mlfsoft/manyo"
INSTALL_PATH = MANYO_PATH
OTHER_MANYO_PAC = ["Utsusemi", "levmar"]
ENV_FILE_NAME = "bashrc.manyo.release"
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
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 = ""
parser = argparse.ArgumentParser(description="The script to compile manyo library source codes")

parser.add_argument('command', choices=['depend', 'man', 'make', 'install', 'clean'],
                    help='command in [depend/man/make/install/clean]')
parser.add_argument('--manyo-path', required=True, help='set MANYO_PATH')
parser.add_argument('--dist-name',
                    choices=["RH6", "RH7", "Ubuntu", "Ubuntu16", "Ubuntu18", "Ubuntu20", "Ubuntu22", "Ubuntu24"],
                    help="Disribution name")
parser.add_argument('--other-modules', choices=["SAS", "DNA"],
                    help="Other modules required if need (default Utsusemi")
parser.add_argument('--numth', type=int, help='set the number of multi-threading', default=2)
tp = lambda x:list(map(int, x.split('.')))
parser.add_argument('--pyver', type=tp, help='Python version')
parser.add_argument('--rev', help='revision number default:YYYYMMDD')
parser.add_argument('--with-para', action='store_true', help='do make command with option -j')
parser.add_argument('--without-para', action='store_true', help='do make command without option -j')
parser.add_argument('--without-depend', action='store_false', help='Not do depend script')
parser.add_argument('--debug', action='store_true', help='turn on the debug mode')

args = parser.parse_args()

do_command = args.command
MANYO_PATH = args.manyo_path
isDebug = args.debug
isWithDepend = args.without_depend
if args.with_para and (not args.without_para):
    isCompPara = True
else:
    isCompPara = False
if args.rev is not None:
    utsusemi_rev = args.rev
if args.pyver is not None:
    PYVER = "{}.{}".format(args.pyver[0], args.pyver[1])
if args.numth is not None:
    NUM_OF_THREADS = args.numth
if args.other_modules is not None:
    other_mods = args.other_modules.split(",")
    OTHER_MANYO_PAC.extend(other_mods)
    for a_mod in OTHER_MANYO_PAC:
        print("OTHER_MANYO_PAC= {}".format(a_mod))
if args.dist_name is not None:
    DIST_NAME = args.dist_name

if (do_command == "clean"):
    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 = ""
    if os.path.exists(os.path.join(os.getcwd(), "Makefile")):
        fo = open(os.path.join(os.getcwd(), "Makefile"), "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("24.04") == 0 or 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"
elif DIST_NAME == "Ubuntu22" or DIST_NAME == "Ubuntu24":
    DIST_NAME = "Ubuntu20"


#########################################################################
# 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 += "./depend; "

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)

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_list = []
env_list.append('#!/bin/bash')
env_list.append('export MANYO_PATH={:s}'.format(MANYO_PATH))

if isNotManyoCore and (MANYO_PATH != INSTALL_PATH):
    env_list.append('export INSTALL_PATH={:s}'.format(INSTALL_PATH))
    envset = 'export LD_LIBRARY_PATH=${MANYO_PATH}/lib:${INSTALL_PATH}/'
    envset += '{:s}/lib:'.format(PACKAGE_NAME)
    envset += '${LD_LIBRARY_PATH}'
    env_list.append(envset)
    envset = 'export PYTHONPATH=${MANYO_PATH}:${INSTALL_PATH}/Manyo/'
    envset += '{:s}:'.format(PACKAGE_NAME)
    envset += '${PYTHONPATH}'
    env_list.append(envset)
else:
    env_list.append(
        'export LD_LIBRARY_PATH=${MANYO_PATH}/lib:${LD_LIBRARY_PATH}')
    env_list.append('export PYTHONPATH=${MANYO_PATH}:${PYTHONPATH}')
env_list.append('export PATH=${MANYO_PATH}/bin:$PATH')


if isDebug:
    for an_env in env_list:
        print(an_env)
else:
    fo = open(os.path.join(os.getcwd(), ENV_FILE_NAME), 'w')
    for ss in env_list:
        fo.write(ss + '\n')
    fo.close()
