#! /usr/bin/env python
import sys
import os
################################################################################
# Compile script for Manyo-lib release version
#    ver 20200214
#    written by Y. Inamura
#########################################################################
man_script="Usage :     %s <command> [options]\n"%(sys.argv[0])
man_script+="""
       command: [depend/man/make/install/clean]
       options: --debug --help --prefix --manyo-path
                --other-modules --numth --pyver
                --rev --without-depend --without-para
                --oldinstalltype
  -------------------------------------------------------
  depend  : depend script
  man     : script to make manual
  make    : make
  install : make install
  clean   : make clean

  --debug          : debug mode
  --help           : show this help
  
  --prefix=/hoge/hogege/hoge
                   : set directory to install
  --manyo-path=/hoge/hogege/hoge
                   : set directory to install with old structures
  
  --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
  --without-para   : not use compile option of -j (default use -j)
  --oldinstalltype : install to old path (/opt/mlfsfot/

"""

#########################################################################
#   CXX            : compiler
#   PYVER          : version of python
#   NUM_OF_THREADS : number of threading
#   PREFIX         : 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
#   DIST_NAME      : name of linux distribution
#########################################################################
CXX            = "g++"
PYVER          = "%s.%s"%(sys.version_info.major, sys.version_info.minor)
NUM_OF_THREADS = 8
PREFIX         = "/opt/mlfsoft/utsusemi"
OTHER_MANYO_PAC= ["Utsusemi"]
ENV_FILE_NAME  = "bashrc.manyo.release"
EXT_LIB_ROOT   = "/usr/local"
DIST_NAME      = ""

isDebug = False
isWithDepend = True
isCompPara = True
isNotManyoCore = True
utsusemi_rev = 0
isOldInstallType = False
if sys.version_info.major==2:
    isOldInstallType = True
distNameDic = ["RH6","RH7","Ubuntu"]
#############################################
# 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","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.find("--rev=")==0:
            utsusemi_rev = int(an_arg[6:])
            print("utsusemi_rev = %d"%utsusemi_rev)
        elif an_arg.find("--pyver=")==0:
            PYVER = an_arg[8:].strip()
            print("PYVER= "+PYVER)
        elif an_arg.find("--numth=")==0:
            NUM_OF_THREADS=int(an_arg[8:])
            print("NUM_OF_THREADS= %d"%(NUM_OF_THREADS))
        elif an_arg.find("--prefix=")==0:
            PREFIX=an_arg[9:]
            isOldInstallType = False
            print("PREFIX="+PREFIX)
        elif an_arg.find("--manyo-path=")==0:
            PREFIX=an_arg[13:]
            isOldInstallType = True
            print("PREFIX="+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= "+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 distNameDic:
                print(" ERROR : --dist-name is invalid")
                sys.exit(-1)
        elif an_arg.find("--oldinstalltype")==0:
            isOldInstallType = True
        else:
            print("Unindentify argument = "+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"):
    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 l in ll:
            print(l)
            if l.find("PACKAGE_NAME") is not -1:
                PACKAGE_NAME=l.split("=")[1].strip()
                break
    if PACKAGE_NAME=="":
        print( "Makefile is invalid. (No PACKAGE_NAME)" )
        sys.exit(1)


#########################################################################
## 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" )

if DIST_NAME=="Ubuntu":
    DIST_PACK = "dist-packages"
else:
    DIST_PACK = "site-packages"

com = ""
if isOldInstallType:
    MANYO_PATH = PREFIX
    com += "export MANYO_PATH={};".format(MANYO_PATH)
    com += "export LIBRARY_PATH=${MANYO_PATH}/lib"
    com += ":{};".format(EXT_LIB_PATH)
    com += "export LD_LIBRARY_PATH=${LIBRARY_PATH};"
    com += "export C_INCLUDE_PATH=/usr/include/python{}:".format(PYVER)
    com += ":${MANYO_PATH}/include"+":{}".format(EXT_INC_PATH)
    for m_pac_name in OTHER_MAN_PAC:
        com += ":${MANYO_PATH}/include/"+"{}".format(m_pac_name)
else:
    MANYO_PATH = os.path.join( PREFIX,"lib","python{}".format(PYVER),DIST_PACK)
    com += "export MANYO_PATH={};".format(MANYO_PATH)
    com += "export PREFIX={};".format(PREFIX)
    com += "export LIBRARY_PATH=${MANYO_PATH}:"+"{};".format(EXT_LIB_PATH)
    com += "export LD_LIBRARY_PATH=${LIBRARY_PATH};"
    com += "export C_INCLUDE_PATH=/usr/include/python{}:".format(PYVER)
    com += ":${PREFIX}/include/Manyo"+":{}".format(EXT_INC_PATH)
    for m_pac_name in OTHER_MAN_PAC:
        com += ":${PREFIX}/include/Manyo/"+"{}".format(m_pac_name)


if DIST_NAME=="Ubuntu":  ## [inamura for Ubuntu 16.04 or later]
    com += ":/usr/include/hdf5/serial"
com += "; "

com += 'export INC_EXT="'
for m_pac_name in OTHER_MAN_PAC:
    com += "%s "%(m_pac_name)
com += '"; '
com += "export CPLUS_INCLUDE_PATH=${C_INCLUDE_PATH};"

if isNotManyoCore and isWithDepend:
    com += "./depend; "

if (do_command!="depend"):
    com += 'make %s '%(do_command)
    if isCompPara:
        com += ' -j '
    if DIST_NAME=="":
        DIST_NAME="Ubuntu"
    com += ' DIST_NAME=%s'%(DIST_NAME)
    if PYVER!="":
        com += ' CXX=%s PyVer=%s NUM_MULTH=%d' % (CXX,PYVER,NUM_OF_THREADS)
    else:
        com += ' CXX=%s NUM_MULTH=%d' % (CXX,NUM_OF_THREADS)
    com += ' UTSUSEMI_REV=%d' % (utsusemi_rev)
    if not isOldInstallType and PYVER!="":
        com += " PY_PREFIX={}".format(MANYO_PATH)

print("command = "+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' % (MANYO_PATH) )

if isOldInstallType:
    env_list.append( 'export LD_LIBRARY_PATH=${MANYO_PATH}/lib:${LD_LIBRARY_PATH}' )
else:
    env_list.append( 'export LD_LIBRARY_PATH=${MANYO_PATH}:${LD_LIBRARY_PATH}' )

if isNotManyoCore:
    env_list.append( 'export PYTHONPATH=${MANYO_PATH}:${MANYO_PATH}/Manyo/%s:${PYTHONPATH}' % (PACKAGE_NAME) )
else:
    env_list.append( 'export PYTHONPATH=${MANYO_PATH}:${PYTHONPATH}' )
env_list.append( 'export PATH={}/bin:$PATH'.format(PREFIX) )


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


