from __future__ import print_function
import os
import sys
import datetime
from xml.etree.ElementTree import ElementTree,fromstring,XML,tostring

"""
Installer of UTSUSEMI
To install UTSUSEMI environment into Ubuntu 12.04, 14.04 and 16.04 LTS with Manyo release version
VerC0.3.8    : Utsusemi4 
VerC0.3.7    : Python 3 only
VerC0.3.6    : DNA Enabled
               Note : Ubuntu packages 'libblas-dev' and 'liblapack-dev' required

VerC0.3.3.3  : bugfix for Default Installation
verC0.3.3.2  : bugfix for SAS (171227)
verC0.3.3.1  : for pyqtgraph
verC0.3.3.0-2: for Ubuntu 16.04LTS
verC0.3.3.0-1: bugfix the issue when overwrite update
verC0.3.3.0 : for release 0.3.3.0
"""
__version__ = "C0.3.8"

############################################################
class InstallToUbuntu:
    ########################################################
    def __init__(self,debug=False):
        """
        Constructor
        @param debug (bool) if debug=True, installer does not touch disk
        @return None
        """
        self.debug = debug
        self.logs = []
        self.logs_index = 0
        self.DefInstBL = 1
        self.cdir = os.getcwd()
        self.MLFDEVROOT = os.path.join( os.environ["HOME"],".MLFENV" )
        if not os.path.exists( self.MLFDEVROOT ):
            os.system( "mkdir %s" % self.MLFDEVROOT )
        self.MLFDEVENVFILE = os.path.join( self.MLFDEVROOT,"environ.xml" )
        
        self.PathDic = {}
        self.PathDic["mlfsoft_root"] = ""  ## for mlfsoft
        self.PathDic["data_root"] = ""     ## for /data/SIK or /data/AMR
        self.PathDic["userhome"] = ""      ## for ~/ana/ and ~/exp/
        self.PathDic["mlfenv"] = ""        ## 
        self.PathDic["environfile"] = ""   
        
        self.MakeDic = {}
        self.MakeDic["CXX"] = ""
        self.MakeDic["PYVER"] = ""
        self.MakeDic["NUM_OF_THREADS"] = ""
        
        self.InstallList = []
        
        self._initialEnviron()
        
        self.dom = None
        
        self.date_fomat = "[%4d/%2d/%2d %2d:%2d:%2d] "
        #self._checkfiles()

    ########################################################
    def _initialEnviron(self):
        self.PathDic["mlfsoft_root"] = "/opt/mlfsoft"  ## for mlfsoft
        self.PathDic["data_root"] = "/data"            ## for /data/SIK or /data/AMR
        self.PathDic["userhome"] = os.environ["HOME"]  ## for ~/ana/ and ~/exp/
        
        self.MakeDic["CXX"] = "g++"
        sysver=sys.version.split(" ")[0]
        sysver_list=sysver.split(".")
        self.MakeDic["PYVER"] = "%1s.%1s"%(sysver_list[0],sysver_list[1])
        self.MakeDic["NUM_OF_THREADS"] = 8

    ########################################################
    def _readEnviron(self):
        """
        """
        if not os.path.exists( self.MLFDEVENVFILE ):
            msg = " There is no saved environment file (%s)." % self.MLFDEVENVFILE
            print(msg)
            self._writeLog(msg)
            self._saveEnviron()
        else:
            fd = open( self.MLFDEVENVFILE,'r')
            dom=ElementTree(file=fd)
            fd.close()

            root_ele = dom.getroot()

            try:
                self.PathDic["mlfsoft_root"] = root_ele.find("mlfSoftRoot").text
                self.PathDic["data_root"] = root_ele.find("mlfBaseDataPath").text
                self.PathDic["userhome"] = root_ele.find("mlfUserHome").text
                self.DefInstBL = int( root_ele.find("mlfInstBL").text )
            except:
                msg = "Invalid parameter file."
                print(msg)
                self._writeLog(msg)

        #self._showEnviron()
        
    ########################################################
    def _showEnviron(self):
        
        print("----------------------------------------------------------")
        print(" Install Directories")
        print("    MLF software root (Manyo, Utsusemi): %s" % self.PathDic["mlfsoft_root"])
        print("    User's home directory              : %s" % self.PathDic["userhome"])
        print("    RAW data  Directory                : %s" % self.PathDic["data_root"])
        print("----------------------------------------------------------")


    ########################################################
    def _saveEnviron(self):
        """
        """
        def s_tab( x ):
            kk = ""
            for i in range(x):
                kk += "    "
            return kk
        
        ss = "<utsusemiOnUbuntuEnviron>\n"
        ss += s_tab(1)+("<mlfSoftRoot>%s</mlfSoftRoot>\n" % (self.PathDic["mlfsoft_root"]))
        ss += s_tab(1)+("<mlfBaseDataPath>%s</mlfBaseDataPath>\n" % (self.PathDic["data_root"]))
        ss += s_tab(1)+("<mlfUserHome>%s</mlfUserHome>\n" % (self.PathDic["userhome"]))
        ss += s_tab(1)+("<mlfInstBL>%d</mlfInstBL>\n" % (self.DefInstBL))
        ss += "</utsusemiOnUbuntuEnviron>\n"

        xml = XML( ss )
        try:
            fd = open( self.MLFDEVENVFILE,"w" )
            fd.write( '<?xml version="1.0" encoding="utf-8"?>\n' )
            tmp=str( tostring(xml,encoding="unicode") )
            fd.write( tmp )
            fd.close()
        except:
            msg = "Cannot open %s for saving instalation parameters." % self.MLFDEVENVFILE
            print(msg)
            self._writeLog(msg)

    ########################################################
    def _checkfiles(self, foldername):
        """
        Check directory or file name required for install
        @param  foldername
        @return None
        """
        self.cdir = os.getcwd()
        src_dir = os.path.join( self.cdir, "src" )
        dlist = os.listdir( src_dir )
        
        isExist = False
        for item in dlist:
            if (item.find( str( foldername ) )!=-1 ) and (os.path.isdir( os.path.join( src_dir, item ) ) ):
                isExist = True
                break
            else:
                msg = "There is no source directory for %s."%( foldername )
                isExist = False
        
        return isExist
    
    ########################################################
    def uninstall(self,delDataFlag=False):
        """
        Uninstall procedure
        @param delDataFlag (bool) if True, delete Raw data and xml files
        @retval 0  No problem
        @retval -1 Error happened
        """

        self._readEnviron()
        
        #InstCode = self.DicInstCode[ self.DefInstBL ]
        #InstDir = os.path.join(self.IROHAroot,('mlf_%s' % InstCode ) )
        coms = []
        coms.append("sudo rm -rf %s" % ( self.PathDic["mlfsoft_root"] ) )
        msg = 'self.PathDic["mlfsoft_root"]= %s' % self.PathDic["mlfsoft_root"]
        self._writeLog(msg)
        
        #coms.append("sudo rm -f /etc/ld.so.conf.d/manyo.conf")
        
        if delDataFlag:
            coms.append("rm -rf %s" % os.path.join( self.PathDic["userhome"],"ana" ) )
            coms.append("rm -rf %s" % os.path.join( self.PathDic["userhome"],"exp" ) )
            coms.append("sudo rm -rf %s" % self.PathDic["data_root"] )

        flist = os.listdir( self.cdir )
        for item in flist:
            if (item.find("manyo")!=-1) and (os.path.isdir(item)):
                coms.append("rm -rf manyo*")
            if (item.find("python")!=-1) and (os.path.isdir(item)):
                coms.append("rm -rf python-*")
            if (item.find("do_make_Utsusemi.py")!=-1):
                coms.append("rm -rf do_make*.py")
            
        try:
            for com in coms:
                os.system(com)
                self._writeLog(com)
        except:
            return -1

        return 0
        

    ########################################################
    def AskPrivateInstallPath(self):
        """

        @param None
        @retval  0    OK
        @retval -1    do nothing
        """

        self.PathDic["mlfsoft_root"] = os.path.join( os.environ["HOME"], "mlfsoft" )
        self.PathDic["data_root"] = os.path.join( os.environ["HOME"], "mlfsoft", "RAWDATA" )
        self.PathDic["userhome"] = os.environ["HOME"]
        
        print("============================================================")
        print("                   Set your install paths")
        while( True ):
            print(" ")
            print("============================================================")
            print(" 1. Path to install Utsusemi software")
            print("   --> %s" % self.PathDic["mlfsoft_root"])
            print(" ")
            print(" 2. Path to Event data directory")
            print("   --> %s" % self.PathDic["data_root"])
            print(" ")
            print(" 3. Path to user directory (for ana/xml or exp/xml)")
            print("   --> %s" % self.PathDic["userhome"])
            print("============================================================")
            print(" ")
            ret=input(">> Which do you change ? [1 to 3. 0 to exit] ")
            if ret=="1":
                r_dir = self._AskNewPath("install Utsusemi software")
                if r_dir!="":
                    self.PathDic["mlfsoft_root"] = r_dir
                continue
            elif ret=="2":
                r_dir = self._AskNewPath("Event data directory")
                if r_dir!="":
                    self.PathDic["data_root"] = r_dir
                continue
            elif ret=="3":
                r_dir = self._AskNewPath("User directory")
                if r_dir!="":
                    self.PathDic["userhome"] = r_dir
                continue
            elif ret=="0":
                break
            else:
                print("Input value is invalid.")
        
        return 0
    ########################################################
    def _AskNewPath(self,title):
        """
        """
        print("Please imput new path to %s = " % title)
        path_in=input(">> ")
        if path_in=="":
            return ""
        
        coms = []
        coms.append( "mkdir -p %s"%(path_in) )
        if -1 == self._doCommands( coms, self.debug ):
            return ""
        
        return path_in
        """
        ret = self._makeNewDir( path_in )
        if ret==-1:
            return ""
        
        return ret
        """

    ########################################################
    def installUbuntuPackages(self):
        """
        Install Ubuntu Package to be required for installation
        @retval 0  No problem
        @retval -1 Error happend
        """
        import subprocess
        tmp = str( subprocess.check_output(["cat","/etc/issue"], universal_newlines=True) )
        tmp_l = tmp.split(" ")
        major_ver_ubuntu = tmp_l[1][:2]

        pkg_list = ['g++','swig',
                    'python3-dev',
                    'libhdf5-dev',
                    'libmxml-dev',
                    'libgsl-dev',
                    'python3-numpy','python3-scipy','python3-matplotlib'
                    ]

        after_pkg_list = []
        if major_ver_ubuntu=="16":
            pkg_list.append( 'libnexus0-dev' )
            pkg_list.append( 'libblas-dev' )
            pkg_list.append( 'liblapack-dev' )
            pkg_list.append( "libboost-all-dev" )
            pkg_list.append( 'python3-pip' )
            #pkg_list.remove( 'python-wxgtk2.8' )
            #pkg_list.append( 'python-wxgtk3.0' )
            #pkg_list.append( 'python-pip' )
            #pkg_list.append( 'python-qt4-gl' )
            #pkg_list.append( 'python-qt4' )
            #pkg_list.append( 'python-opengl' )
            after_pkg_list.append( 'python3-pyside' )
            after_pkg_list.append( 'python3-pyqt4' )
            after_pkg_list.append( 'python3-pyqt4.qtopengl' )
            after_pkg_list.append( 'python3-pyqtgraph' )
        elif major_ver_ubuntu=="18":
            pkg_list.append( 'make' )
            pkg_list.append( 'libnexus0-dev' )
            pkg_list.append( 'libblas-dev' )
            pkg_list.append( 'liblapack-dev' )
            pkg_list.append( 'libboost-dev' )
            pkg_list.append( 'libboost-serialization-dev' )
            pkg_list.append( 'libboost-filesystem-dev' )
            pkg_list.append( 'libboost-system-dev' )
            pkg_list.append( 'libboost-program-options-dev' )
            pkg_list.append( 'python3-pip' )
            pkg_list.append( 'python3-pyside' )
            pkg_list.append( 'python3-pyqt4' )
            pkg_list.append( 'python3-pyqt4.qtopengl' )
            pkg_list.append( 'python3-pyqtgraph' )
            pkg_list.append( 'libcanberra-gtk-module' )

        elif major_ver_ubuntu=="20":
            pkg_list.append( 'libnexus-dev' )
            pkg_list.append( 'libboost-dev' )
            pkg_list.append( 'libboost-serialization-dev' )
            pkg_list.append( 'libboost-filesystem-dev' )
            pkg_list.append( 'libboost-system-dev' )
            pkg_list.append( 'libboost-program-options-dev' )
            pkg_list.append( 'python3-pyside2.qtcore' )
            pkg_list.append( 'python3-pyside2.qtwidgets' ) # pkg_list.append( 'python3-pyside2.qtgui' )
            
        else:
            msg="Ubuntsu Linux version is not suitable."
            raise UserWarning(msg)
        
        coms = []
        if major_ver_ubuntu=="16":
            for pkg in pkg_list:
                coms.append( ( 'sudo apt-get install -y %s' % pkg) )
            coms.append( 'sudo pip3 install --upgrade pip' )
            coms.append( 'sudo pip3 install --upgrade PyOpenGL' )
        elif major_ver_ubuntu=="18":
            for pkg in pkg_list:
                coms.append( ( 'sudo apt install -y %s' % pkg) )
            coms.append( 'sudo pip3 install --upgrade pip' )
            coms.append( 'sudo pip3 install --upgrade PyOpenGL' )
        elif major_ver_ubuntu=="20":
            for pkg in pkg_list:
                coms.append( ( 'sudo apt install -y %s' % pkg) )

        for pkg in after_pkg_list:
            coms.append( ( 'sudo apt-get install -y %s' % pkg) )

        return self._doCommands( coms, self.debug )

    ########################################################
    def _doCommands(self, coms, debugFlag=False,ignoreErr=False):
        """
        Execute command list
        @param coms (list of string) commands to be executed
        @param debugFlag (bool) if True, do not touch files on disk
        @retval 0 No problem
        @retval -1 Error happened
        """
        if (debugFlag!=True) and (debugFlag!=False):
            msg = "doCommands: cannot invalid flag"
            print(msg)
            self._writeLog(msg)
            return -1

        for com in coms:
            com_sudo = ""
            if not debugFlag:
                
                ff = os.system(com)
                msg = "_doCommands::%s res=%d" % (com,ff)
                self._writeLog(msg)
                if ff!=0:
                    msg = "_doCommands::sudo %s" % com
                    self._writeLog(msg)
                    com_sudo = 'sudo ' + com
                    if os.system(com_sudo)!=0:
                        if not ignoreErr:
                            msg = "sudo fails: %s" % com_sudo
                            self._writeLog(msg)
                            return -1

            if com_sudo!="":
                self.logs.append(com_sudo)
            else:
                self.logs.append(com)
            
        return 0
    ########################################################
    def _writeLogs(self):
        """
        Save logs to file
        
        """
        fo = open("install_log.txt",'a')
        fo.write( "                            \n" )
        fo.write( "------- Write Logs ---------\n" )
        for log_line in self.logs[self.logs_index:]:
            dt=datetime.datetime.today()
            out_log = (self.date_fomat%(dt.year,dt.month,dt.day,dt.hour,dt.minute,dt.second))+log_line+"\n"
            fo.write( out_log )
        fo.write( "----------------------------\n" )
        fo.close()
        self.logs_index = len(self.logs)

    ########################################################
    def _writeLog(self,message):
        """
        """
        fo = open("install_log.txt","a")
        dt=datetime.datetime.today()
        df = (self.date_fomat%(dt.year,dt.month,dt.day,dt.hour,dt.minute,dt.second))
        fo.write( df+"Message >> "+message+"\n" )
        fo.close()

    ########################################################
    def Check_Scenario(self, scenario, pre_install_pack=[] ):
        """
        Scenario item = ( <source name>,[<required source name>,<...>],<source type> )
        <source name> : directory name like 'manyo-core', 'python-utsusemi'
        <source type> : 'manyo' or 'python' or 'python-utsusemi'
                        if manyo -> compile source
                        if python -> copy directory to /opt/mlfsoft/<source name>
                        if python-utsusemi -> copy direcotry to /opt/mlfsoft/python-utsusemi/
        """
        dicSe = pre_install_pack[:]
        self.InstallList = []
        for pname,depps,src_type in scenario:
            if pname in dicSe:
                pass
            else:
                dicSe.append( pname )
            for deppack in depps:
                if deppack in dicSe:
                    pass
                else:
                    msg = "Check_Scenario >> Senario is invalid. %s must be installed before %s."%(deppack, pname )
                    print(msg)
                    self._writeLog(msg)
                    return False
            if self._checkfiles(pname):
                self.InstallList.append( (pname, src_type) )
            else:
                msg = "Check_Scenario >> checkfiles is invalid : No source folder for (%s)."%(pname)
                print(msg)
                self._writeLog(msg)
                return False

        print( "self.InstallList = ",self.InstallList )
        return True
        
    ########################################################
    def Install_as_Scenario(self, scenario=[], pre_installed_pack=[] ):
        """
        
        """
        if len(scenario)!=0:
            if not self.Check_Scenario( scenario, pre_installed_pack ):
                return False
                
        elif len(self.InstallList)==0:
            return False
        
        
        self.InstallList.reverse()
        for dname, a_type in self.InstallList:
            if a_type=="libs":
                if dname == "lib-levmar":
                    if self.Install_Levmar(dname):
                        return False
        
        for dname, a_type in self.InstallList:
            if a_type=="manyo":
                do_make_file_path = os.path.join( self.cdir,"src",dname,"do_make_Utsusemi.py" )
                if os.path.exists( do_make_file_path):
                    ro = open( do_make_file_path, "r" )
                    do_make_coms = ro.readlines()
                    ro.close()
                    out_make_coms = []
                    for a_com in do_make_coms:
                        if a_com.find("CXX")==0:
                            out_make_coms.append( 'CXX            = "%s"\n'%(self.MakeDic["CXX"]) )
                        elif a_com.find("PYVER")==0:
                            out_make_coms.append( 'PYVER          = "%s"\n'%(self.MakeDic["PYVER"]) )
                        elif a_com.find("NUM_OF_THREADS")==0:
                            out_make_coms.append( 'NUM_OF_THREADS = %d\n'%(self.MakeDic["NUM_OF_THREADS"]) )
                        elif a_com.find("MANYO_PATH")==0:
                            out_make_coms.append( 'MANYO_PATH     = "%s"\n'%(os.path.join( self.PathDic["mlfsoft_root"],"manyo") ) )
                        elif a_com.find("isCompPara")==0:
                            out_make_coms.append( "isCompPara = False\n" )
                        else:
                            out_make_coms.append( a_com )
                    rw = open( os.path.join( self.cdir,"src","do_make_Utsusemi.py" ), "w" )
                    if rw==None:
                        return False
                    rw.writelines( out_make_coms )
                    rw.close()
        if os.path.exists( os.path.join( self.cdir,"src","do_make_Utsusemi.py" ) ):
            pass
        else:
            return False
        
        self.InstallList.reverse()
        coms = []
        for dname, a_type in self.InstallList:
            print( "## Install_as_Scenario step : %s, %s"%(dname, a_type) )
            if a_type=="manyo":
                coms.append( "mkdir -p %s"%(self.PathDic["mlfsoft_root"]) )
                coms.append( "chmod 777 -R %s"%(self.PathDic["mlfsoft_root"]) )
                coms.append( "cd %s; python3 ../do_make_Utsusemi.py install"%(os.path.join(self.cdir,"src",dname ) ) )
            elif a_type=="python":
                p1 = os.path.join( self.cdir,"src",dname )
                p2 = os.path.join( self.PathDic["mlfsoft_root"], dname )
                coms.append( "mkdir -p %s"%(p2) )
                coms.append( "cp -rf %s/* %s"%(p1,p2) )
            #elif a_type=="python-utsusemi":
            #    p1 = os.path.join( self.cdir,"src",dname )
            #    fname = dname[ (len(a_type)+1): ]
            #    p2 = os.path.join( self.PathDic["mlfsoft_root"],a_type,fname )
            #    coms.append( "mkdir -p %s"%(p2) )
            #    coms.append( "cp -rf %s/* %s"%(p1,p2) )
            elif a_type=="env":
                p1 = os.path.join( self.cdir,"src",dname )
                fname = dname[ (len(a_type)+1): ]
                coms.append( "cp -rf %s/* %s"%(p1,self.PathDic["userhome"]) )
        
        if self._doCommands( coms )<0:
            return False
            
        print(" ")
        print("-----------------------------------------------")
        print("  Install of ")
        for a_pack in self.InstallList:
            print("       - %s "%( a_pack[0] ))
        print("                                were completed.")
        print("-----------------------------------------------")
        print(" ")
        
        return True

    ########################################################
    def Install_Levmar(self,dname):
        levmar_path =os.path.join(self.cdir,"src",dname,"2.5" )
        manyo_lib_path = os.path.join(self.PathDic["mlfsoft_root"],"manyo","lib")
        manyo_inc_path = os.path.join(self.PathDic["mlfsoft_root"],"manyo","include")
        coms = []
        coms.append( "cd %s; make"%(levmar_path) )
        coms.append( "sudo mkdir -p %s"%(self.PathDic["mlfsoft_root"]) )
        coms.append( "sudo chmod 777 -R %s"%(self.PathDic["mlfsoft_root"]) )
        coms.append( "mkdir -p %s"%(manyo_lib_path) )
        coms.append( "mkdir -p %s"%(manyo_inc_path) )
        coms.append( "cp -rf %s/liblevmar.* %s "%(levmar_path,manyo_lib_path) )
        coms.append( "cp -rf %s/*.h %s "%(levmar_path,manyo_inc_path) )

        if self._doCommands( coms )<0:
            print("Installation of Levmar Library failed.")
            return False
        
    ########################################################
    def make_Utsusemi_Env(self):
        """
        
        """

        user_dirs = []
        user_dirs.append( os.path.join( self.PathDic["userhome"],"ana" ) )
        user_dirs.append( os.path.join( self.PathDic["userhome"],"ana","tmp" ) )
        user_dirs.append( os.path.join( self.PathDic["userhome"],"ana","xml" ) )
        user_dirs.append( os.path.join( self.PathDic["userhome"],"exp" ) )
        user_dirs.append( os.path.join( self.PathDic["userhome"],"exp","log" ) )
        user_dirs.append( os.path.join( self.PathDic["userhome"],"exp","xml" ) )
        
        coms = []
        for udir in user_dirs:
            if not os.path.exists( udir ):
                coms.append( 'mkdir ' + udir )
        
        coms.append( "mkdir -p %s"%(self.PathDic["mlfsoft_root"]) )
        coms.append( "sudo chmod 777 -R %s"%(self.PathDic["mlfsoft_root"]) )
        coms.append( 'mkdir -p %s'%(self.PathDic["data_root"]) )
        coms.append( 'sudo chmod 777 -R %s'%(self.PathDic["data_root"]) )
        
        ret = self._doCommands( coms )
        if ret==-1:
            msg =  "Error happends on executing command %s." % self.logs[-1]
            print(msg)
            self._writeLog(msg)
            self._writeLogs()
            raise UserWarning(msg)

        self._writeLogs()

        self._saveEnviron()
        
        print(" ")
        print("-------------------------------------------------------")
        print("  Utsusemi Base Environment Setting has been completed.")
        print("-------------------------------------------------------")
        print(" ")

        
    ########################################################
    def add_EnvironmaneVariables(self,BLcode):
        """
        """
        bash_file = os.path.join( self.PathDic["mlfsoft_root"],"python-utsusemi","utsusemi",BLcode,"bashrc.py3.%3s"%(BLcode) )
        if not os.path.exists(bash_file):
            msg = "Error: There is no bashrc template file (%s)\n" % (bash_file)
            print(msg)
            self._writeLog(msg)
            raise UserWarning(msg)
        
        fo = open( bash_file, "r" )
        bash_conts = fo.readlines()
        fo.close()
        
        rewrite_lines = []
        for a_line in bash_conts:
            if a_line[:3]=="XXX":
                rewrite_lines.append( "XXX=%s\n"%(BLcode) )
            elif a_line[:2]=="BL":
                pass
            elif a_line.find("MLFSOFT_PATH=")==0:
                rewrite_lines.append( "MLFSOFT_PATH=%s\n"%(self.PathDic["mlfsoft_root"]) )
            elif a_line[:25]=="UTSUSEMI_EXT_LIBRARY_PATH":
                rewrite_lines.append( "UTSUSEMI_EXT_LIBRARY_PATH=%s\n"%(self.PathDic["mlfsoft_root"]) )
            else:
                rewrite_lines.append(a_line)
        
        fw = open( bash_file, "w" )
        fw.writelines( rewrite_lines )
        fw.close()
        
        # add bashrc
        ss = '\n'
        ss+= '# For Utsusemi environment\n'
        ss+= 'if [ -f %s ]; then\n'%(bash_file)
        #ss+= '       source %s\n' %(bash_file)
        ss+= '       alias %s="source %s"\n' %(BLcode,bash_file)
        ss+= 'fi\n'
        
        try:
            fw = open( "add.bashrc", "w" )
        except:
            msg = "Cannot open add.bashrc."
            print(msg)
            self._writeLog(msg)
            return -1
        fw.write(ss)
        fw.close()
        
        coms = []
        coms.append('cat add.bashrc >> ~/.bashrc')
        coms.append('rm -rf add.bashrc')
        coms.append('mkdir -p %s'%(os.path.join( self.PathDic["data_root"],BLcode ) ) )
        coms.append('sudo chmod 777 -R %s'%(self.PathDic["data_root"]) )

        if (BLcode=="DNA"):
            coms.append("cp -rf src/environ-DNA/ana/* %s"%(os.path.join( self.PathDic["userhome"],"ana" )))

        ret = self._doCommands( coms, self.debug )
        if ret==-1:
            return -1
            
        ## End safely
        print(" ")
        print("----------------------------------------------------------")
        print("  Utsusemi Environment Setting for %3s has been completed."%(BLcode))
        print("----------------------------------------------------------")
        print(" ")
        return 0



PACK_DIC = { "MANYO-CORE":("manyo-core",[],"manyo"),
             "MANYO-UTSU":("manyo-utsusemi",["manyo-core"],"manyo"),
             "PYTHON-UTSU":("python-utsusemi",["manyo-utsusemi"],"python"),
             "PYTHON-UGAO":("python-ugao",["manyo-core"],"python"),
             "MANYO-TKT":("manyo-TKtools",["manyo-core"],"manyo"),
             "MANYO-SAS":("manyo-SAS",["manyo-utsusemi"],"manyo"),
             "PYTHON-EMAKI":("python-emaki",["python-utsusemi"],"python"),
             "MANYO-DNA":("manyo-DNA",["manyo-utsusemi"],"manyo"),
             "LIB-LEVMAR":("lib-levmar",[],"libs"),
             "MANYO-LEVMAR":("manyo-LevmarTools",["manyo-core","lib-levmar"],"manyo"),
             "ENVIRON-DNA":("environ-DNA",["manyo-DNA"],"env")
             }

DEF_PACK_ORDER = ["MANYO-CORE","MANYO-UTSU","MANYO-TKT","MANYO-SAS","PYTHON-UTSU","PYTHON-UGAO",
                  "PYTHON-EMAKI","LIB-LEVMAR","MANYO-LEVMAR","MANYO-DNA","ENVIRON-DNA" ]

def UtsusemiDefaultInstall(num_of_cores=8):
    
    ITU=InstallToUbuntu()
    ITU.installUbuntuPackages()
    ITU.MakeDic["NUM_OF_THREADS"] = num_of_cores
    install_scenario = []
    for a_key in DEF_PACK_ORDER:
        install_scenario.append( PACK_DIC[a_key] )
    
    if ITU.Check_Scenario( install_scenario ):
        ret = ITU.Install_as_Scenario( install_scenario )
        if (ret):
            ITU.make_Utsusemi_Env()
            ITU.add_EnvironmaneVariables("SIK")
            ITU.add_EnvironmaneVariables("AMR")
            ITU.add_EnvironmaneVariables("HPN")
            ITU.add_EnvironmaneVariables("SAS")
            ITU.add_EnvironmaneVariables("TKtools")
            ITU.add_EnvironmaneVariables("DNA")
            print("  Utsusemi Default Install was completed.")
    



if __name__== '__main__':
    if sys.version.split(" ")[0]<"3.0.0":
        print( "ERROR : This script requires Python 3.x")
        print( "        Your python version is %s"%(sys.version.split(" ")[0]))
        sys.exit(-1)
    
    if (len(sys.argv)==2) and (sys.argv[1]=="-all"):
        UtsusemiDefaultInstall()
    else:
        ITU=InstallToUbuntu()
        print("=================================================================")
        print("       Welcome to Utsusemi software installer (ver.%s) " % (__version__))
        print("=================================================================")
        menu_title = " in common directory "
        continue_flag = True
        while( continue_flag ):
            force_return_flag = False
            ITU._showEnviron()
            print("""

-----------------------------------------------------------------
       Utsusemi Install Main Menu for Debian or Ubuntu
-----------------------------------------------------------------
  
  0... Install ALL modules for an instrument
         note: this will DELETE all of modules installed before.

  ----------------------------------------------------
  1... Required Ubuntu Packages
  2... Utsusemi software (Manyo-lib and common code)
  3... Utsusemi software for each BL

  7... Change Install Directories
  
  9... Uninstall

others.. exit
-----------------------------------------------------------------""")

            ret=input(">> Which ? ")
            if not ret in ["0","1","2","3","7","9"]:
                print("Exit without installation.")
                continue_flag = False
                force_return_flag = True
            else:
                choice = int(ret)
                
                if choice==9:
                    print(" ")
                    print("Do you want to delete Raw data or xml data, too ?")
                    ret=input(">> answer ?[y/N] ")
                    if ret=="Y" or ret=="y":
                        ret = ITU.uninstall(True)
                    else:
                        ret = ITU.uninstall()
                    if ret==-1:
                        print("Failed to uninstall.")
                        sys.exit()
                    print("Uninstall is finished.")
                    print(" ")

                elif choice==7:
                    while(True):
                        print("""  ------------------------------------------------
  Install Directories Menu
  ----------------
  1..... Change Directories to private area
  2..... Return Directories to MLF default
  3..... Load Previous Install Directories
  4..... Show Present Setting
  
  0..... Return to Main menu
""")
                        ret1 = input(">> Which ? ")
                        if not ret1 in ["0","1","2","3","4"]:
                            continue
                        if ret1=="0":
                            force_return_flag = True
                            break
                        elif ret1=="1":
                            ret = ITU.AskPrivateInstallPath()
                            if ret!=0:
                                print("Something wrong")
                            menu_title = " in private directory "
                        elif ret1=="2":
                            ITU._initialEnviron()
                        elif ret1=="3":
                            ITU._readEnviron()
                            ITU._showEnviron()
                        else:
                            ITU._showEnviron()


                elif choice==1:
                    ITU.installUbuntuPackages()

                elif choice==2:
                    print("For compiling Manyo-lib, please select the number of threads.")
                    ret=input(">> How many threads? [>1, default=1] ")
                    try:
                        nc = int(ret)
                    except:
                        nc = 8
                    ITU.MakeDic["NUM_OF_THREADS"] = nc
                    install_scenario = []
                    install_scenario.append( PACK_DIC["MANYO-CORE"] )
                    install_scenario.append( PACK_DIC["MANYO-UTSU"] )
                    install_scenario.append( PACK_DIC["PYTHON-UTSU"] )
                    install_scenario.append( PACK_DIC["PYTHON-UGAO"] )
                    install_scenario.append( PACK_DIC["PYTHON-EMAKI"] )

                    if ITU.Check_Scenario( install_scenario ):
                        ret = ITU.Install_as_Scenario( install_scenario )
                        if (ret):
                            pass
                        else:
                            print(" ")
                            print("!!!!!!!!!  Install Failed !!!!!!!!!")
                            print("     Utsusemi is NOT installed.")
                            print("-----------------------------------")
                            print(" Please send install_log.txt to ")
                            print("  your contact person.")

                elif choice==3:
                    print(" ")
                    ret = input(">> Have you installed ManyoLib and Utsusemi Base system ( menu number 2 ) [y/N]? ")
                    if ret!="Y" and ret!="y":
                        pass
                    else:
                        print("---------------------------------")
                        print("  Select Package you install")
                        print("---------------------------------")
                        print(" [ 1] BL01 4SEASONS (SIK)")
                        print(" [ 2] BL02 DNA (DNA)")
                        print(" [14] BL14 AMATERAS (AMR)")
                        print(" [11] BL11 PLANET (HPN)")
                        print(" [15] BL15 Taikan (SAS)")
                        print(" [TK] TKtools")
                        print(" [-1] Exit menu")
                        print("---------------------------------")
                        print(" ")

                        pre_installed_pack=["manyo-core","manyo-utsusemi","python-utsusemi"]
                        while(True):
                            install_scenario = []
                            ret_BL=input(">> Which Package? ")
                            ret_BL = ret_BL.strip().upper()
                            BL_name=""
                            if ret_BL=="1":
                                #install_scenario.append( PACK_DIC["PYTHON-UTSU-SIK"] )
                                BL_Name="SIK"
                                break
                            if ret_BL=="2":
                                install_scenario.append( PACK_DIC["LIB-LEVMAR"] )
                                install_scenario.append( PACK_DIC["MANYO-LEVMAR"] )
                                install_scenario.append( PACK_DIC["MANYO-DNA"] )
                                #install_scenario.append( PACK_DIC["PYTHON-UTSU-DNA"] )
                                install_scenario.append( PACK_DIC["ENVIRON-DNA"] )
                                BL_Name="DNA"
                                break
                            elif ret_BL=="14":
                                #install_scenario.append( PACK_DIC["PYTHON-UTSU-AMR"] )
                                BL_Name="AMR"
                                break
                            elif ret_BL=="11":
                                #install_scenario.append( PACK_DIC["PYTHON-UTSU-HPN"] )
                                BL_Name="HPN"
                                break
                            elif ret_BL=="15":
                                install_scenario.append( PACK_DIC["MANYO-SAS"] )
                                #install_scenario.append( PACK_DIC["PYTHON-UTSU-SAS"] )
                                BL_Name="SAS"
                                break
                            elif ret_BL=="TK":
                                install_scenario.append( PACK_DIC["MANYO-TKT"] )
                                #install_scenario.append( PACK_DIC["PYTHON-UTSU-TKT"] )
                                BL_Name="TKtools"
                                break
                            elif ret_BL=="-1":
                                break
                            else:
                                print(' "%s" is Invalid value'%(ret))

                        if ret_BL!="-1":
                            ITU.make_Utsusemi_Env()
                        if len(install_scenario)!=0:
                            if ITU.Check_Scenario( install_scenario,pre_installed_pack ):
                                ret = ITU.Install_as_Scenario( install_scenario, pre_installed_pack )
                                if not ret:
                                    print(" ")
                                    print("!!!!!!!!!  Install Failed !!!!!!!!!")
                                    print("     Utsusemi is NOT installed.")
                                    print("-----------------------------------")
                                    print(" Please send install_log.txt to ")
                                    print("  your contact person.")
                            else:
                                print("Install Scenario is invalid.")
                        
                        ITU.add_EnvironmaneVariables(BL_Name)

                elif choice==0:
                    print("For compiling Manyo-lib, please select the number of threads.")
                    ret=input(">> How many threads? [>1, default=1] ")
                    try:
                        nc = int(ret)
                    except:
                        nc = 8
                    UtsusemiDefaultInstall(nc)

                else:
                    print(" Invalid input ")

            if force_return_flag:
                pass
            else:
                ret=input(">> Back to Main Menu? [Y/n] ")
                if ret=="N" or ret=="n":
                    continue_flag = False
                else:
                    continue_flag = True
                        
                        
