import os
import sys
import datetime

ver = float(sys.version_info[0]) + float(sys.version_info[1]) * 0.1
if ver < 2.5:
    from elementtree.ElementTree import ElementTree, fromstring, XML, tostring
else:
    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.7-1  : Enabled for Ubuntu 18.04
VerC0.3.7    : DNA disabled for 0.3.7 (under construction)
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.7-1"

############################################################


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++"
        self.MakeDic["PYVER"] = "2.7"
        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 = file(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')
            fd.write(tostring(xml))
            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 = raw_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 = raw_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
        """
        coms = []

        pkg_list = ['g++', 'subversion', 'swig',
                    'python-dev', 'python-wxgtk2.8', 'python-vtk',
                    'python-numpy', 'python-scipy', 'python-matplotlib', 'python-h5py',
                    'libhdf5-serial-dev', 'libmxml-dev', 'libgsl0-dev', 'libbz2-dev',
                    'libnexus0-dev', 'libblas-dev', 'liblapack-dev'
                    ]

        coms.append("sudo apt-get update")
        coms.append("sudo apt-get upgrade")
        self._doCommands(coms, self.debug, True)

        # [inamura 140828]-->
        # search and add packages for boost
        import commands
        tmp = commands.getoutput("cat /etc/issue")
        tmp_l = tmp.split(" ")
        ver_utsu = tmp_l[1]
        if ver_utsu[:2] == "12":
            tmp = commands.getoutput("sudo apt-cache search libboost1")
            tmp_lines = tmp.split("\n")
            libboost_list = []
            for i in tmp_lines:
                tmp_list = i.split(" - ")
                if tmp_list[0].find("-all-dev") != -1:
                    libboost_list.append(tmp_list[0])
            libboost_list.sort()
            pkg_list.append(libboost_list[-1])
        elif ver_utsu[:2] == "14":
            pkg_list.append()
            pkg_list.append("libboost-all-dev")
        elif ver_utsu[:2] == "16":
            pkg_list.append("libgsl-dev")
            pkg_list.append("libboost-all-dev")
            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')
        elif ver_utsu[:2] == "18":
            pkg_list.remove('python-vtk')
            pkg_list.remove('python-wxgtk2.8')
            pkg_list.append('python-wxgtk3.0')
            pkg_list.append("python-vtk6")
            pkg_list.append("libgsl-dev")
            pkg_list.append("libboost-all-dev")
            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')
        else:
            msg = "Ubuntsu Linux version is not suitable."
            raise UserWarning(msg)
        # -->[inamura 140828]

        coms = []
        if ver_utsu[:2] == "18":
            for pkg in pkg_list:
                coms.append(('sudo apt install -y %s' % pkg))
        else:
            for pkg in pkg_list:
                coms.append(('sudo apt-get install -y %s' % pkg))

        coms.append('pip install pyqtgraph')

        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 not isinstance(debugFlag, bool):
            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

        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 is 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:
            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; python ../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)
        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 "ERROR", 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", BLcode, "bashrc.%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[:17] == "export MANYO_PATH":
                rewrite_lines.append("export MANYO_PATH=%s\n" % (os.path.join(self.PathDic["mlfsoft_root"], "manyo")))
            elif a_line[:15] == "UTSUSEMIPY_PATH":
                rewrite_lines.append("UTSUSEMIPY_PATH=%s\n" % (os.path.join(self.PathDic["mlfsoft_root"], "python-utsusemi")))
            elif a_line[:15] == "PYUTSUSEMI_PATH":
                rewrite_lines.append("PYUTSUSEMI_PATH=%s\n" % (os.path.join(self.PathDic["mlfsoft_root"], "python-utsusemi")))
            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-UTSU-SIK": ("python-utsusemi-SIK", ["python-utsusemi"], "python-utsusemi"),
            "PYTHON-UTSU-AMR": ("python-utsusemi-AMR", ["python-utsusemi"], "python-utsusemi"),
            "PYTHON-UTSU-HPN": ("python-utsusemi-HPN", ["python-utsusemi"], "python-utsusemi"),
            "MANYO-TKT": ("manyo-TKtools", ["manyo-core"], "manyo"),
            "PYTHON-UTSU-TKT": ("python-utsusemi-TKtools", ["manyo-TKtools", "python-utsusemi"], "python-utsusemi"),
            "MANYO-SAS": ("manyo-SAS", ["manyo-utsusemi"], "manyo"),
            "PYTHON-UTSU-SAS": ("python-utsusemi-SAS", ["python-utsusemi"], "python-utsusemi"),
            "PYTHON-EMAKI": ("python-emaki", ["python-utsusemi"], "python"),
            "MANYO-DNA": ("manyo-DNA", ["manyo-utsusemi"], "manyo"),
            "LIB-LEVMAR": ("lib-levmar", [], "libs"),
            "MANYO-LEVMAR": ("manyo-levmar", ["manyo-core", "lib-levmar"], "manyo"),
            "PYTHON-UTSU-DNA": ("python-utsusemi-DNA", ["manyo-levmar"], "python-utsusemi"),
            "ENVIRON-DNA": ("environ-DNA", ["python-utsusemi-DNA"], "env")
            }


def UtsusemiDefaultInstall(num_of_cores=8):
    print ""
    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 "  "
    print " [ALL] All"
    print " [-1] Exit menu"
    print "---------------------------------"
    print "Which beamline do you want to install ? "
    print "   Input sample : BL01 and BL14 => 1,14"
    ret_BL = raw_input(">> BL = ")
    ret_BL_list = ret_BL.split(",")
    InputBLList = []
    # ENABLE_BL = ["1","2","11","14","15","TK"]
    ENABLE_BL = ["1", "11", "14", "15", "TK"]
    for a_BL in ret_BL_list:
        a_BL = a_BL.strip().upper()
        if a_BL == "ALL":
            InputBLList = ENABLE_BL[:]
        elif a_BL in ENABLE_BL:
            InputBLList.append(a_BL)
        elif a_BL == "-1":
            InputBLList = []

    if len(InputBLList) == 0:
        return
    InputBLList.sort()

    ITU = InstallToUbuntu()
    ITU.installUbuntuPackages()
    ITU.MakeDic["NUM_OF_THREADS"] = num_of_cores
    install_scenario = []
    install_scenario.append("MANYO-CORE")
    install_scenario.append("MANYO-UTSU")
    install_scenario.append("PYTHON-UTSU")
    env_list = []
    for a_BL in InputBLList:
        if a_BL == "1":
            install_scenario.append("PYTHON-UTSU-SIK")
            env_list.append("SIK")
        if a_BL == "2":
            install_scenario.append("MANYO-DNA")
            install_scenario.append("LIB-LEVMAR")
            install_scenario.append("MANYO-LEVMAR")
            install_scenario.append("PYTHON-UTSU-DNA")
            install_scenario.append("ENVIRON-DNA")
            env_list.append("DNA")
        if a_BL == "11":
            install_scenario.append("PYTHON-UTSU-HPN")
            env_list.append("HPN")
        if a_BL == "14":
            install_scenario.append("PYTHON-UTSU-AMR")
            env_list.append("AMR")
        if a_BL == "15":
            install_scenario.append("MANYO-SAS")
            install_scenario.append("PYTHON-UTSU-SAS")
            install_scenario.append("PYTHON-EMAKI")
            env_list.append("SAS")
        if a_BL == "TK":
            install_scenario.append("MANYO-TKT")
            install_scenario.append("PYTHON-UTSU-TKT")

    install_scenario_pack = []
    for a_scenario in install_scenario:
        install_scenario_pack.append(PACK_DIC[a_scenario])

    if ITU.Check_Scenario(install_scenario_pack):
        ret = ITU.Install_as_Scenario(install_scenario_pack)
        if (ret):
            ITU.make_Utsusemi_Env()
            for a_env in env_list:
                ITU.add_EnvironmaneVariables(a_env)
            print "  Utsusemi Default Install was completed."


if __name__ == '__main__':
    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 = raw_input(">> Which ? ")
            if ret not 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 = raw_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 = raw_input(">> Which ? ")
                        if ret1 not 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 = raw_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-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 = raw_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 = raw_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["MANYO-DNA"] )
                                install_scenario.append( PACK_DIC["LIB-LEVMAR"] )
                                install_scenario.append( PACK_DIC["MANYO-LEVMAR"] )
                                install_scenario.append( PACK_DIC["PYTHON-UTSU-DNA"] )
                                install_scenario.append( PACK_DIC["ENVIRON-DNA"] )
                                BL_Name="DNA"
                                break
                            """
                            if 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 len(install_scenario) != 0:
                            if ITU.Check_Scenario(install_scenario, pre_installed_pack):
                                ret = ITU.Install_as_Scenario(install_scenario, pre_installed_pack)
                                if (ret):
                                    ITU.make_Utsusemi_Env()
                                    ITU.add_EnvironmaneVariables(BL_Name)
                                else:
                                    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."

                elif choice == 0:
                    print "For compiling Manyo-lib, please select the number of threads."
                    ret = raw_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 = raw_input(">> Back to Main Menu? [Y/n]")
                if ret == "N" or ret == "n":
                    continue_flag = False
                else:
                    continue_flag = True
