#!/usr/bin/env python
# :set ts=4
# :set expandtab
# :%retab!

import logging
import os,sys,time,socket,threading,copy,StringIO,cPickle,subprocess,fcntl,struct,signal,shutil,commands
import re,ConfigParser
while True:
    try:
        import xml.etree.cElementTree as ET
        break
    except ImportError:
        pass
    try:
        import cElementTree as ET
        break
    except ImportError:
        pass
    break;

class cGlobalData:
    pass


gd = cGlobalData()

def _make_dirs(dirs):
    for make_path in dirs:
        try:
            os.makedirs(make_path, 0755)
        except OSError, e:
            logging.debug(e)
            
def main():
    global gd
    gd.longbit = 32
    gd.packetType = 1
    gd.bPrivate = 0
    gd.bSilent = 0
    packType = 1
    allStep = 0
    nowStep = 1
    showType = 0
    installType = 0
    stepFollow = []

    funcSets = {"server":install_server, "apache":install_apache, "nginx":install_nginx, "tomcat":install_tomcat}
    gd.AccurateKernelVer = ['2.6.32-358.el6.i686', '2.6.32-431.23.3.el6.i686', '2.6.32-431.23.3.el6.x86_64', '3.10.0-123.9.3.el7.x86_64']
    gd.kernelVer = ['2.6.18-308.el5', '3.2.0-29-generic', '3.13.0-32-generic', '2.6.18', '2.6.32', '3.0', '3.2', '3.5', '3.8', '3.10', '3.11', '3.13', '3.14', '3.15', '3.16', '3.18', '3.19', '4.0', '4.1']
    
    has_web_pkt = False
    for i in range(1, len(sys.argv)):
        if (sys.argv[i] == "-s"):
            stepFollow.append("server")
        elif (sys.argv[i] == "-a"):
            stepFollow.append("apache")
            has_web_pkt = True
        elif (sys.argv[i] == "-n"):
            stepFollow.append("nginx")
            has_web_pkt = True
        elif (sys.argv[i] == "-t"):
            stepFollow.append("tomcat")
        elif (sys.argv[i] == "-p"):
            gd.bPrivate = 1
        elif (sys.argv[i] == "-silent"):
            gd.bSilent = 1
            
    if (len(sys.argv) == 3 and sys.argv[2] == "-q"):
        installType = 1

    sOut,sErr = fPopen("getconf LONG_BIT")
    if (int(sOut) == 32):
        gd.longbit = 32
    else:
        gd.longbit = 64

    mybit = 0
    sOut,sErr = fPopen("file -L dependpkg/bin/sdsvrd | awk '{print $3}'")
    if (int(sOut[0:2]) == 32):
        mybit = 32
    else:
        mybit = 64

    if (mybit == 32 and gd.longbit == 64):
        print "You need 64 bit safedog version!\nExit installation!\n"
        doExit()

    if (mybit == 64 and gd.longbit == 32):
        print "You need 32 bit safedog version!\nExit installation!\n"
        doExit()        
        
    #if is version = 2.7.x
    gd.isOldVer = 0
    sOut,sErr = fPopen("sdcmd check | grep 'sVersion= 2.7.' | awk '{print $2}'")
    if (len(sOut) > 0 or os.path.exists("/etc/safedog/sdsvrd.conf")):
        if (len(sOut) == 0):
            gd.oldVer = "2.7.X"
        else:
            gd.oldVer = sOut
        print("step 0/3, start cover install safedog " + gd.oldVer)
        gd.isOldVer = 1
        stop_old_server()
        backup_user_data()
        uninstall_old_server()
    else:
        stop_server()
    
    create_dir()

    allStep = 2
    if (has_web_pkt):
        web_type = getSelectType()
        if (web_type != "web_no"):
            if (web_type in stepFollow):
                allStep += 1
            
    print "step "+str(nowStep)+"/"+str(allStep)+", start install common lib",
    install_common()
    print_resault("start install common lib",0)    
    for key in stepFollow:
        nowStep = nowStep + 1
        #funcSets[key](nowStep,allStep, 0, installType)
        #    continue
        #if (key == web_type or web_type == "web_all"):
        #    funcSets[key](nowStep,allStep, 0, installType)
        if nowStep > 3:
            nowStep = 3
        if(key == "apache" or key == "nginx"):
            if (key == web_type or web_type == "web_all"):
                funcSets[key](nowStep,allStep,0,installType)
        else:
            funcSets[key](nowStep,allStep,0,installType)
            
    if (gd.isOldVer):       
        uninstall_old_common()
    
    restart_common()
    if (os.system("which sdacm 1>/dev/null 2>&1") != 0 and os.system("which sdsvrd 1>/dev/null 2>&1") != 0 ):   
        uninstall_common()

    print("Install Completely!")
    return  


def install_server(now_step,all_step,show_type,install_type):
    global gd
    gd.isTest=False
    gd.iStepAll=all_step
    gd.iStepNow2=now_step
    gd.iStepNow=0
    #!!! total step is set manually because it is difficult to calculate by program.
    #!!! Please make sure to change the value when total installation steps were changed!   
    gd.iServerTotalStep=5 

    if(not show_type == 0):
        try:
            for i in range(1,11):
                os.system("echo -n -e \"\\r"+"step "+str(gd.iStepNow2)+"/"+str(gd.iStepAll)+", start Install Server Defense Module in \"" +str(10-i)+ " seconds,please enter \"CTRL+c\" to skip.")
                time.sleep(1)
        except KeyboardInterrupt:
            print("Cancel install Server Defense Module")
            return
    
    os.system("echo -n -e \"\\r"+"step "+str(gd.iStepNow2)+"/"+str(gd.iStepAll)+", start Install Server Defense Module                                                    \"")

    sOut,sErr = fPopen("getenforce")
    if(sOut[0:9] == "Enforcing"):
        print("Selinux is running, can not install safedog!")
        return
    
    fPopen("chmod +x ./dependpkg/bin/udinstall")
    sOut,sErr = fPopen("./dependpkg/bin/udinstall -c")  
    if( len(sOut)>0 and sOut[0] == "0" ):
        print("Version error, Can not install!")
        return
        
    fPopen("mkdir -p /etc/safedog/server/backup/baklibsd;rm -rf /etc/safedog/server/backup/baklibsd/*")
    fPopen("cp -rf /etc/safedog/libs/safedog /etc/safedog/server/backup/baklibsd/ 2>/dev/null")
    fPopen("rm -rf /etc/safedog/libs/safedog/* 2>/dev/null")

    gd.filelibcryptopath,gd.filelibsslpath = findOpenSsl(gd.longbit)
    if(len(gd.filelibcryptopath) < 9 or len(gd.filelibsslpath) < 9):
        print("need openssl library for installing safedog for linux.")
        print("installing exiting")
        return False

    if( len(sys.argv) > 1 ):
        if(sys.argv[1] == "test"):
            gd.isTest = True

    if(not initGD()):
        return
    
    print "\n  step "+stepnow()+", checking os release version...",
    sOut,sErr = fPopen("cat /etc/issue")
    sIssueRes = sOut.lower()
    iSelect = 0
    idxArrOs=1
    while( idxArrOs <=7 ):
        if( sIssueRes.find(gd.arrOsDes[idxArrOs]) != -1):
            iSelect = idxArrOs
            break
        else:
            idxArrOs += 1

    if( iSelect > 7 or iSelect<1 ):
        sOut,sErr = fPopen("cat /etc/redhat-release")
        sIssueRes = sOut.lower()
        iSelect = 0
        idxArrOs=1
        while( idxArrOs <=7 ):
            if( sIssueRes.find(gd.arrOsDes[idxArrOs]) != -1):
                iSelect = idxArrOs
                break
            else:
                idxArrOs += 1

    if( iSelect > 7 or iSelect<1 ):
        print ("%s")%(gd.sInstallTip)
        inSelect=raw_input()
        while( not inSelect.isdigit() or  int(inSelect) > 7 or int(inSelect) < 1):
            print ("%s")%(gd.sInstallTip)
            inSelect=raw_input()
        iSelect = int(inSelect)
        if( iSelect > 7 or iSelect<1 ):
            print("We are so sorry, the safedog don't support your os!")
            print("installing exiting!")
            return 
    print_resault(", checking os release version...",0)
    os.system("./dependpkg/bin/udinstall -n %d -t %d &"%(gd.iStepNow,gd.iServerTotalStep))
    print "  step "+stepnow()+", check app needed...",
    for sApp in gd.arrApplist:
        sOut,sErr = fPopen("which %s"%sApp)
        if( len(sOut) == 0 ):
            print_resault(", check app needed...",2)
            print "need "+sApp+" to install safedog for linux."
            print "installing exiting!"
            return
            
    print_resault(", check app needed...",0)
    os.system("./dependpkg/bin/udinstall -n %d -t %d &"%(gd.iStepNow,gd.iServerTotalStep))
    os.system("./dependpkg/bin/udinstall -n %d -t %d &"%(gd.iStepNow,gd.iServerTotalStep))

    print "  step "+stepnow()+", installing file...",
    for sCmd in gd.arrCmds:
        sOut,sErr=fPopen(sCmd)
        if( len(sErr) >0 ):
            print_resault(", installing file...",2)
            print "command:'%s' failed!"%sCmd
            print sErr
            return

    # for antian, copy files if there is
    if (os.path.exists('./dependpkg/antian')):
        os.system('cp -a -f -r ./dependpkg/antian /etc/safedog/server/')

    print_resault(", installing file...",0)
    os.system("./dependpkg/bin/udinstall -n %d -t %d &"%(gd.iStepNow,gd.iServerTotalStep))
    print "  step "+stepnow()+", start service...",
    if (gd.isOldVer):
        recovery_user_data()
    fPopen("/usr/bin/sdsvrd -s %s -v %s"%(gd.arrOs[iSelect],gd.sVersion))
    #time.sleep(2)
    #fPopen("killall sdsvrd")
    for i in range(0,3):
        fPopen("/usr/bin/sdstart")
        sOut,sErr = fPopen("ps f -e | grep \"sdsvrd -d\"| grep -v grep |awk '{print $1}'")
        if(len(sOut)>0):
            break
        else:
             if( i==2):
                print "\033[1;31;10m\nstart sdserver fail, please install safedog again\033[0m"
                return
        time.sleep(1)
        
    print_resault(", start service...", 0)

    print "  step "+stepnow()+", save safedog install info..."
    os.system("./dependpkg/bin/udinstall -n %d -t %d &"%(gd.iStepNow,gd.iServerTotalStep))
    
    print_resault(" Tips:", 3)
    print "  (1)safedog install directory:\033[1;32;10m /etc/safedog \033[0m"
    print "  (2)install safedog version:\033[1;32;10m " + gd.sVersion + " \033[0m"
    if (gd.isOldVer):
        print "  (3)cover install old version:" + gd.oldVer
        
    print "  install safedog completely"
    return

def doExit():
    sys.exit(1)
    return

def fPopen(aCmd):
    p=subprocess.Popen(aCmd, shell=True, bufsize=4096,stdin=subprocess.PIPE, stdout=subprocess.PIPE, stderr=subprocess.PIPE, close_fds=True)
    sOut = p.stdout.read()
    sErr = p.stderr.read()
    return (sOut,sErr)

def initGD():
    global gd

    gd.sVersion="2.8.16709"
    gd.arrOs=['','ubuntu','centos','fedora','rhel','suse','asianux','debian','else']
    gd.arrOsDes=['','ubuntu','centos','fedora','hat','suse','asianux','debian','else']
    gd.sInstallTip="please select the correct release version name of your os:\n"
    gd.sInstallTip+="[1] ubuntu\n"
    gd.sInstallTip+="[2] centos\n"
    gd.sInstallTip+="[3] fedora\n"
    gd.sInstallTip+="[4] rhel (Red Hat Enterprise Linux)\n"
    gd.sInstallTip+="[5] openSUSE\n"
    gd.sInstallTip+="[6] redflag (Asianux Server 4.0)\n"
    gd.sInstallTip+="[7] debian\n"
    gd.sInstallTip+="[8] else or I don't know\n"

    gd.arrApplist="locate find python cat grep egrep awk netstat df free iptables zcat ifconfig sort uniq head hostname cp echo touch ps bash tail vmstat du mv tar mkdir rm chown chmod service killall kill ifdown ifup sed basename date uname ls cut diff iptables-save iptables-restore".split()

    gd.arrCmds=[]
    gd.arrCmds.append("chmod -R 700 ./*")
    gd.arrCmds.append("chmod +x ./dependpkg/lib/*")
    gd.arrCmds.append("chmod +x ./dependpkg/bin/* ")
    gd.arrCmds.append("chmod +x ./dependpkg/script/* ")
    gd.arrCmds.append("rm -rf /etc/safedog/server/conf/safedoginfo.conf >/dev/null 2>&1")
    gd.arrCmds.append("cp -a -f -r ./dependpkg/lib/libsafedog/* /etc/safedog/libs/safedog/")
    gd.arrCmds.append("cp -a -f -r -P ./dependpkg/lib/libcommon/* /etc/safedog/libs/sdcommon/")
    
    gd.arrCmds.append("ln -s -f /etc/safedog/libs/safedog/libmysqlclient.so /etc/safedog/libs/safedog/libmysqlclient.so.15")
    gd.arrCmds.append("ln -s -f /etc/safedog/libs/safedog/libcrypt-2.5.so /etc/safedog/libs/safedog/libcrypt.so.1")
    gd.arrCmds.append("ln -s -f /etc/safedog/libs/safedog/libnsl-2.5.so /etc/safedog/libs/safedog/libnsl.so.1")
        
    gd.arrCmds.append("mkdir -p /etc/cloudhelper/examine/cmd/")
    gd.arrCmds.append("mkdir -p /etc/cloudhelper/examine/report/")      
    gd.arrCmds.append("mkdir -p /etc/cloudhelper/examine/module/")  
    gd.arrCmds.append("cp -a -f -r ./dependpkg/lib/libsafedog/libmod_*.so /etc/cloudhelper/examine/module/")
    
    gd.arrCmds.append("cp -a -f ./dependpkg/bin/uduninstall /etc/safedog/server/bin/")
    gd.arrCmds.append("ln -s -f /etc/safedog/server/bin/uduninstall /usr/bin/uduninstall")
    gd.arrCmds.append("cp -a -f ./dependpkg/bin/sdsvrd /etc/safedog/server/bin/")
    gd.arrCmds.append("ln -s -f /etc/safedog/server/bin/sdsvrd /usr/bin/sdsvrd")
    gd.arrCmds.append("cp -a -f ./dependpkg/bin/sdwebdir /etc/safedog/server/bin/")
    gd.arrCmds.append("ln -s -f /etc/safedog/server/bin/sdwebdir /usr/bin/sdwebdir")
    gd.arrCmds.append("cp -a -f ./dependpkg/bin/sdrtdefendupdate /etc/safedog/server/bin/")
    gd.arrCmds.append("ln -s -f /etc/safedog/server/bin/sdrtdefendupdate /usr/bin/sdrtdefendupdate")
    gd.arrCmds.append("cp -a -f ./dependpkg/bin/udcenter /etc/safedog/sdcc/bin/")
    gd.arrCmds.append("ln -s -f /etc/safedog/sdcc/bin/udcenter /usr/bin/udcenter")
    #gd.arrCmds.append("cp -a -f ./dependpkg/bin/sd_autoexmn /etc/safedog/server/bin/")
    #gd.arrCmds.append("ln -s -f /etc/safedog/server/bin/sd_autoexmn /usr/bin/sd_autoexmn")
    gd.arrCmds.append("cp -a -f ./dependpkg/bin/udinstall /etc/safedog/server/bin/")
    gd.arrCmds.append("ln -s -f /etc/safedog/server/bin/udinstall /usr/bin/udinstall")
    gd.arrCmds.append("cp -a -f ./dependpkg/bin/sduibin /etc/safedog/server/bin/")
    gd.arrCmds.append("ln -s -f /etc/safedog/server/bin/sduibin /usr/bin/sduibin")
    gd.arrCmds.append("cp -a -f ./dependpkg/bin/sdcmd /etc/safedog/server/bin/")
    gd.arrCmds.append("ln -s -f /etc/safedog/server/bin/sdcmd /usr/bin/sdcmd")
    gd.arrCmds.append("cp -a -f ./dependpkg/bin/udpro /etc/safedog/sdcc/bin/")
    gd.arrCmds.append("ln -s -f /etc/safedog/sdcc/bin/udpro /usr/bin/udpro")
    gd.arrCmds.append("cp -a -f ./dependpkg/bin/sdalarm /etc/safedog/sdcc/bin/")
    gd.arrCmds.append("ln -s -f /etc/safedog/sdcc/bin/sdalarm /usr/bin/sdalarm")    
    gd.arrCmds.append("cp -a -f ./dependpkg/bin/sdcloud /etc/safedog/server/bin/")
    gd.arrCmds.append("ln -s -f /etc/safedog/server/bin/sdcloud /usr/bin/sdcloud")
    #gd.arrCmds.append("cp -a -f ./dependpkg/bin/sdmonitor /etc/safedog/server/bin/")
    #gd.arrCmds.append("ln -s -f /etc/safedog/server/bin/sdmonitor /usr/bin/sdmonitor")

    gd.arrCmds.append("cp -a -f ./dependpkg/script/sdstart /etc/safedog/server/script/")
    gd.arrCmds.append("ln -s -f /etc/safedog/server/script/sdstart /usr/bin/sdstart")
    gd.arrCmds.append("cp -a -f ./dependpkg/script/udboot /etc/safedog/sdcc/script/")
    gd.arrCmds.append("ln -s -f /etc/safedog/sdcc/script/udboot /usr/bin/udboot")
    gd.arrCmds.append("cp -a -f ./dependpkg/script/safedog /etc/safedog/server/script/")
    gd.arrCmds.append("ln -s -f /etc/safedog/server/script/safedog /usr/bin/safedog")
    gd.arrCmds.append("cp -a -f ./dependpkg/script/sdui /etc/safedog/server/script/")
    gd.arrCmds.append("ln -s -f /etc/safedog/server/script/sdui /usr/bin/sdui")
    #gd.arrCmds.append("cp -a -f ./dependpkg/script/sdboot /etc/safedog/server/script/")
    #gd.arrCmds.append("ln -s -f /etc/safedog/server/script/sdboot /usr/bin/sdboot")
    gd.arrCmds.append("cp -a -f ./dependpkg/script/sdsetos /etc/safedog/server/script/")
    gd.arrCmds.append("ln -s -f /etc/safedog/server/script/sdsetos /usr/bin/sdsetos")
                 
    gd.arrCmds.append("mkdir -p /etc/safedog/server/examine")
    gd.arrCmds.append("cp -a -f ./dependpkg/examine/* /etc/safedog/server/examine/")
    gd.arrCmds.append("mkdir -p /etc/safedog/server/conf")
    gd.arrCmds.append("cp -a -f ./dependpkg/conf/* /etc/safedog/server/conf/")

    gd.arrCmds.append("cp -a -f ./dependpkg/script/safedog /etc/init.d/")
    #gd.arrCmds.append("cp -a -f ./dependpkg/script/sdboot  /etc/init.d/")
    gd.arrCmds.append("cp -a -f ./dependpkg/script/udboot  /etc/init.d/")

    #gd.arrCmds.append("rm -f /etc/rc2.d/S99sdboot")
    #gd.arrCmds.append("rm -f /etc/rc3.d/S99sdboot")
    #gd.arrCmds.append("rm -f /etc/rc4.d/S99sdboot")
    #gd.arrCmds.append("rm -f /etc/rc5.d/S99sdboot")

    gd.arrCmds.append("cp -a -f ./dependpkg/script/udboot  /etc/init.d/")
    gd.arrCmds.append("rm -rf /etc/rc2.d/S99udboot")
    gd.arrCmds.append("rm -rf /etc/rc3.d/S99udboot")
    gd.arrCmds.append("rm -rf /etc/rc4.d/S99udboot")
    gd.arrCmds.append("rm -rf /etc/rc5.d/S99udboot")

    gd.arrCmds.append("rm -f /etc/safedog/libs/safedog/libcrypto.so*")
    gd.arrCmds.append("ln -s -f /etc/safedog/libs/sdcc/libcrypto.so.6 /etc/safedog/libs/safedog/libcrypto.so")
    gd.arrCmds.append("rm -f /etc/safedog/libs/safedog/libssl.so*")
    gd.arrCmds.append("ln -s -f /etc/safedog/libs/sdcc/libssl.so.6 /etc/safedog/libs/safedog/libssl.so")
    gd.arrCmds.append("rm -f /etc/safedog/libs/safedog/libcurl.so.*")
    gd.arrCmds.append("ln -s -f /etc/safedog/libs/sdcc/libcurl.so.4 /etc/safedog/libs/safedog/libcurl.so.4")
    gd.arrCmds.append("rm -f /etc/safedog/libs/safedog/libcurl.so")
    gd.arrCmds.append("ln -s -f /etc/safedog/libs/sdcc/libcurl.so.4 /etc/safedog/libs/safedog/libcurl.so")

    gd.arrCmds.append("rm -rf /etc/safedog/libs/sdcommon/libboost_*.so")
    gd.arrCmds.append("ln -s -f /etc/safedog/libs/sdcommon/libboost_system.so.1.49.0 /etc/safedog/libs/sdcommon/libboost_system.so")
    gd.arrCmds.append("ln -s -f /etc/safedog/libs/sdcommon/libboost_thread.so.1.49.0 /etc/safedog/libs/sdcommon/libboost_thread.so")
    gd.arrCmds.append("ln -s -f /etc/safedog/libs/sdcommon/libboost_filesystem.so.1.49.0 /etc/safedog/libs/sdcommon/libboost_filesystem.so")
    gd.arrCmds.append("ln -s -f /etc/safedog/libs/sdcommon/libboost_regex.so.1.49.0 /etc/safedog/libs/sdcommon/libboost_regex.so")
    
    gd.arrCmds.append("chmod 755 /etc/safedog")
    gd.arrCmds.append("chmod -R 700 /etc/safedog/libs/sdcc")
    gd.arrCmds.append("chmod -R 700 /etc/safedog/libs/sdcommon")
    gd.arrCmds.append("chmod -R 700 /etc/safedog/libs/safedog")
    #gd.arrCmds.append("chmod -R 700 /etc/safedog/libs/nginx")
    #gd.arrCmds.append("chmod -R 700 /etc/safedog/libs/apache")
    gd.arrCmds.append("chmod -R 700 /etc/safedog/bin/")
    gd.arrCmds.append("chmod -R 700 /etc/safedog/script/")
    gd.arrCmds.append("chmod -R 700 /etc/safedog/conf/")
    gd.arrCmds.append("chmod -R 700 /etc/safedog/logs/")
    gd.arrCmds.append("chmod -R 700 /etc/safedog/server/bin")
    gd.arrCmds.append("chmod -R 700 /etc/safedog/sdcc/bin")
    gd.arrCmds.append("mv /etc/isolation_info_bak/isolation_files/ /etc/safedog/server/examine/ 2>/dev/null");
    gd.arrCmds.append("mv /etc/isolation_info_bak/isolation_list.conf /etc/safedog/server/examine/ 2>/dev/null");
    gd.arrCmds.append("mv /etc/isolation_info_bak/handlecache.db /etc/safedog/server/conf/ 2>/dev/null");
    gd.arrCmds.append("rm -rf /etc/isolation_info_bak 2>/dev/null");
    gd.arrCmds.append("cp -a -f ./dependpkg/SafedogIDCType.conf /etc/safedog/server/conf/ 2>/dev/null") 
    if(os.path.exists("/etc/sdsvrd.conf")):
        gd.arrCmds.append("cp -a -f /etc/sdsvrd.conf /etc/safedog/server/conf/")
        gd.arrCmds.append("rm -f /etc/sdsvrd.conf")
    if(os.path.exists("/etc/SafedogIDCType.conf.bak")): 
        gd.arrCmds.append("cp -a -f /etc/SafedogIDCType.conf.bak /etc/safedog/server/conf/SafedogIDCType.conf")
        gd.arrCmds.append("rm -f /etc/SafedogIDCType.conf.bak")

    gd.sConfFile="/etc/safedog/server/conf/sdsvrd.conf"
    gd.sConfFileBak="/etc/safedog/server/backup/sdsvrd.conf.bak"
    
    return True

def findOpenSsl(bit):
    SearchPaths = []
    if (bit == 64):
        SearchPaths.append("/usr/lib64/")
        SearchPaths.append("/lib64/")
    SearchPaths.append("/usr/lib/")
    SearchPaths.append("/lib/")
    FileDir = ""
    FileNamePre = "lib"
    FileNameCore1 = "crypto"
    FileNameCore2 = "ssl"
    FileNameExt = ".so"
    FilePath1 = ""
    FilePath2 = ""
    FindAll = False
    sAllLibs = ""
    for FileDir in SearchPaths:
        sOut,sErr = fPopen("ls %s%s%s%s*"%(FileDir, FileNamePre, FileNameCore1, FileNameExt))
        sAllLibs += sOut
    sAllLibs = sAllLibs.strip()
    arrAllLibs = sAllLibs.split("\n")

    for i in arrAllLibs:
        FilePath1 = i
        if ( os.path.isfile(FilePath1) and (not os.path.isdir(FilePath1))):
            sOut,sErr = fPopen("file -L %s | awk '{print $3}'"%i)
            if(int(sOut[0:2]) == gd.longbit):
                sPathTmp = FilePath1
                idx1 = sPathTmp.find(FileNameCore1)
                while(idx1  > 0):
                    FilePath2 = sPathTmp[0:idx1] + FileNameCore2 + sPathTmp[idx1+len(FileNameCore1):]
                    sPathTmp = FilePath2
                    idx1 = sPathTmp.find(FileNameCore1, idx1 + 2)

                if (os.path.isfile(FilePath2) and (not os.path.isdir(FilePath2))):
                    sOut,sErr = fPopen("file -L %s | awk '{print $3}'"%i)
                    if (int(sOut[0:2]) == gd.longbit):
                        FindAll = True
                        break;
                        
    if (FindAll):
        return (FilePath1, FilePath2)

    sAllLibs = ""
    FileNameTmp = FileNamePre + FileNameCore1 + FileNameExt
    for i in SearchPaths:
        sOut,sErr = fPopen("find %s -name %s\\* 2>/dev/null | grep -v /etc/safedog/libs/sdcc | grep -v /etc/safedog/libs/safedog"%(i,FileNameTmp))
        sAllLibs += sOut

    sAllLibs = sAllLibs.strip()
    arrAllLibs = sAllLibs.split("\n")

    for i in arrAllLibs:
        FilePath1 = i
        if ( os.path.isfile(FilePath1) and (not os.path.isdir(FilePath1))):
            sOut,sErr = fPopen("file -L %s | awk '{print $3}'"%i)
            if(int(sOut[0:2]) == gd.longbit):
                sPathTmp = FilePath1
                idx1 = sPathTmp.find(FileNameCore1)
                while(idx1  > 0):
                    FilePath2 = sPathTmp[0:idx1] + FileNameCore2 + sPathTmp[idx1+len(FileNameCore1):]
                    sPathTmp = FilePath2
                    idx1 = sPathTmp.find(FileNameCore1,idx1+2)


                if ( os.path.isfile(FilePath2) and (not os.path.isdir(FilePath2))):
                    sOut,sErr = fPopen("file -L %s | awk '{print $3}'"%i)
                    if(int(sOut[0:2]) == gd.longbit):
                        FindAll = True
                        break;
    if( FindAll ):
        return (FilePath1,FilePath2)
    return ("","")

def stepnow():
    global gd
    gd.iStepNow += 1
    return str(gd.iStepNow2)+"."+str(gd.iStepNow)
    
def get_sdcc_version(sdccpath):
    version = ""
    cmd = sdccpath + ' -v'
    (status, output) = commands.getstatusoutput(cmd)
    if(status==0):
        version = output
        cmd = 'ps -Ao pid,args|grep -v grep | grep "' + sdccpath + ' *-v"'
        (status, output) = commands.getstatusoutput(cmd)
        if(status==0) and (len(output)!=0):
            lines = output.split('\n')
            for str in lines:
                temp=str.lstrip()
                pid=int(temp.split(' ')[0])
                os.kill(pid, 9)
    return version

def is_cover_sdcc():
    ver1=get_sdcc_version('sdcc')
    ver2=get_sdcc_version('./dependpkg/bin/sdcc')
    
    if(len(ver2)== 0):
        ver2="2.0"
    if(len(ver1)==0) or (ver2 >= ver1):
        return 1
    else:
        return 0
        
def print_resault(buf,type):
    lens=len(buf)
    print_len=86

    if(type == 0):
        print("\033[1;32;10m"),
        print(" ".ljust(print_len-lens)+"[ok]"), 
    elif(type == 1):
        print("\033[1;33;10m"),
        print(" ".ljust(print_len-lens)+"[warn]"), 
    elif(type == 2):
        print("\033[1;31;10m"),
        print(" ".ljust(print_len-lens)+"[error]"), 
    elif(type == 3):
        print("\033[1;32;10m"),
        print(buf),
    print("\033[0m")

def stop_server():
    sOut,sErr = fPopen("ps f -e | grep \"sdmonitor\"| grep -v grep |awk '{print $1}'")
    if(len(sOut)>0):
        print("stop safedog server ....")
        fPopen("rmmod sddev")
        fPopen("sdmonitor -QUIT")
        for i in range(0,30):
            time.sleep(1)
            sOut,sErr = fPopen("ps f -e | grep \"sdmonitor\"| grep -v grep |awk '{print $1}'")
            if(len(sOut)>0):
                continue
            else:
                 break;
                 
def restart_common():
    fPopen("sdmonitor -r sdcc")
    fPopen("sdmonitor -r udcenter")

def install_kernel_driver():
    kVersion = "12107"
    fPopen("rmmod sddev")
    kernel_ver,err=fPopen("uname -r")
    ver = kernel_ver.strip('\n')
    flag = 0
    
    if(len(ver) > 0):
        idxKernel = 0
        idxAccurateKernel = 0

        while(idxAccurateKernel < len(gd.AccurateKernelVer)):
            if(ver == gd.AccurateKernelVer[idxAccurateKernel]):
                os.system("/etc/safedog/sdcc/bin/SDDownload -k -v " + kVersion+"_" + gd.AccurateKernelVer[idxAccurateKernel] + ">/dev/null &")
                flag = 1
                break
            else:
                idxAccurateKernel += 1

        if(flag == 0):
            while( idxKernel < len(gd.kernelVer)):          
                if(ver.startswith(gd.kernelVer[idxKernel])):
                    os.system("/etc/safedog/sdcc/bin/SDDownload -k -v " + kVersion + "_" + gd.kernelVer[idxKernel] + "_" + str(gd.longbit) + " >/dev/null &")
                    break
                else:
                    idxKernel += 1

def create_dir():
    arrDirs2Make=[
        "/etc/safedog/",
        "/etc/safedog/libs/",
        "/etc/safedog/libs/sdcc/",
        "/etc/safedog/libs/sdcommon/",
        "/etc/safedog/libs/safedog/", 
        "/etc/safedog/bin/", 
        "/etc/safedog/script/", 
        "/etc/safedog/conf/", 
        "/etc/safedog/logs/", 
        "/etc/safedog/server/", 
        "/etc/safedog/server/backup/", 
        "/etc/safedog/server/conf/", 
        "/etc/safedog/server/dmp/", 
        "/etc/safedog/server/kernelsafedog/", 
        "/etc/safedog/server/monitor/", 
        "/etc/safedog/server/script/", 
        "/etc/safedog/server/bin/", 
        "/etc/safedog/server/update/", 
        "/etc/safedog/server/examine/", 
        "/etc/safedog/server/examine/isolation_files/",
        "/etc/safedog/server/examine/report/",
        "/etc/safedog/server/examine/packets/",
        "/etc/safedog/server/cloudoprt/",
        "/etc/safedog/sdcc/",
        "/etc/safedog/sdcc/bin/", 
        "/etc/safedog/sdcc/backup/", 
        "/etc/safedog/sdcc/script/",
        "/etc/safedog/sdcc/dmp/",
        "/etc/safedog/sdcc/plugin/",
        "/etc/safedog/sdcc/plugin/plugin_wrapper.d/",
        "/etc/safedog/sdcc/conf/",
        "/etc/safedog/sdcc/update"]
        
    for sDir in arrDirs2Make:
        try:
            os.makedirs(sDir,0700)
        except:
            pass

        if (not os.path.isdir(sDir)):
            print("create directory:'%s' failed!"%sDir)
            print("installing exiting!")
            return
    return
    
def install_common():
    global gd
    gd.arrOsDes=['','ubuntu','centos','fedora','hat','suse','asianux','debian','else']
    fPopen("chmod -R 700 ./*")
    fPopen("chmod +x ./dependpkg/lib/*")
    fPopen("chmod +x ./dependpkg/bin/* ")
    fPopen("chmod +x ./dependpkg/script/* ")
    fPopen("rm -rf /etc/safedog/libs/sdcommon/libboost_*.so")
    fPopen("cp -a -f -r -P ./dependpkg/lib/libcommon/* /etc/safedog/libs/sdcommon/")
    fPopen("ln -s -f /etc/safedog/libs/sdcommon/libboost_system.so.1.49.0 /etc/safedog/libs/sdcommon/libboost_system.so")
    fPopen("ln -s -f /etc/safedog/libs/sdcommon/libboost_thread.so.1.49.0 /etc/safedog/libs/sdcommon/libboost_thread.so")
    fPopen("ln -s -f /etc/safedog/libs/sdcommon/libboost_filesystem.so.1.49.0 /etc/safedog/libs/sdcommon/libboost_filesystem.so")
    fPopen("ln -s -f /etc/safedog/libs/sdcommon/libboost_regex.so.1.49.0 /etc/safedog/libs/sdcommon/libboost_regex.so")
    fPopen("chmod -R 700 /etc/safedog/libs/sdcommon")
    fPopen("cp -a -f ./dependpkg/bin/sdmonitor /etc/safedog/sdcc/bin")
    fPopen("ln -s -f /etc/safedog/sdcc/bin/sdmonitor /usr/bin/sdmonitor")
    fPopen("mkdir -p /etc/safedog/sdcc/plugin/command/config")
    fPopen("mkdir -p /etc/safedog/sdcc/plugin/timertask/config")

    fPopen("rm -rf /etc/sd_uninstall")
    fPopen("mkdir -p /etc/sd_uninstall/install_files/safedogwz_linux"+str(gd.longbit))
    fPopen("mkdir -p /etc/sd_uninstall/install_files/safedog_nginx_linux"+str(gd.longbit))
    fPopen("cp -f safedog_uninstall.py /etc/safedog/script/")
    fPopen("cp -f uninstall.py /etc/sd_uninstall/") 
    fPopen("cp -f uninstall_2x.py /etc/sd_uninstall/install_files/")
    fPopen("cp -f uninstall_3x.py /etc/sd_uninstall/install_files/") 
    fPopen("cp -f ./safedogwz_linux"+str(gd.longbit)+"/uninstall.sh " +"/etc/sd_uninstall/install_files/safedogwz_linux"+str(gd.longbit))
    fPopen("cp -f ./safedog_nginx_linux"+str(gd.longbit)+"/uninstall.sh " +"/etc/sd_uninstall/install_files/safedog_nginx_linux"+str(gd.longbit))       
    fPopen("ln -s -f /etc/safedog/script/safedog_uninstall.py /usr/bin/safedog_uninstall")
    
    fPopen("rm -f /etc/safedog/sdcc/bin/SDDownload")
    fPopen("cp -a -f ./dependpkg/bin/SDDownload /etc/safedog/sdcc/bin/");
    fPopen("ln -s -f /etc/safedog/sdcc/bin/SDDownload /usr/bin/SDDownload");
    
    fPopen("mkdir -p /etc/safedog/sdcc/backup/baklibsd;rm -rf /etc/safedog/sdcc/backup/baklibsd/*")
    fPopen("cp -rf /etc/safedog/libs/sdcc /etc/safedog/sdcc/backup/baklibsd/ 2>/dev/null")
    fPopen("rm -rf /etc/safedog/libs/sdcc/*")
    fPopen("cp -a -f -r -P ./dependpkg/lib/libsdcc/* /etc/safedog/libs/sdcc/")
    fPopen("mv /etc/safedog/libs/sdcc/so_dir /etc/safedog/sdcc/plugin/")
    
    fPopen("cp -a -f ./dependpkg/AntivirusCustom.ini /etc/safedog/server/conf/")
    fPopen("python ./install_cgroup.py")
    #install_kernel_driver()
    
    if (is_cover_sdcc()):
        sOut,sErr = fPopen("cat /etc/issue")
        sIssueRes = sOut.lower()
        iSelect = 0
        idxArrOs = 1
        while (idxArrOs <= 7):
            if (sIssueRes.find(gd.arrOsDes[idxArrOs]) != -1):
                iSelect = idxArrOs
                break
            else:
                idxArrOs += 1
        
        fPopen("cp -a -f -r -P ./dependpkg/lib/libsdcc/* /etc/safedog/libs/sdcc/")
        fPopen("cp -a -f ./dependpkg/bin/sdcc /etc/safedog/sdcc/bin/")
        fPopen("ln -s -f /etc/safedog/sdcc/bin/sdcc /usr/bin/sdcc")
        fPopen("cp -a -f ./dependpkg/bin/udcenter /etc/safedog/sdcc/bin/")
        fPopen("ln -s -f /etc/safedog/sdcc/bin/udcenter /usr/bin/udcenter")
        fPopen("cp -a -f ./dependpkg/bin/udpro /etc/safedog/sdcc/bin/udpro")
        fPopen("ln -s -f /etc/safedog/sdcc/bin/udpro /usr/bin/udpro")
        
        fPopen("cp -a -f ./dependpkg/script/runsdcc /etc/safedog/sdcc/script/")
        fPopen("ln -s -f /etc/safedog/sdcc/script/runsdcc /usr/bin/runsdcc")
        fPopen("cp -a -f ./dependpkg/script/sdccboot /etc/safedog/sdcc/script/")
        fPopen("ln -s -f /etc/safedog/sdcc/script/sdccboot /usr/bin/sdccboot")
        fPopen("cp -a -f ./dependpkg/script/udboot /etc/safedog/sdcc/script/")
        fPopen("ln -s -f /etc/safedog/sdcc/script/udboot /usr/bin/udboot")
        
        fPopen("cp -a -f ./dependpkg/trust.crt /etc/safedog/sdcc")
        fPopen("cp -a -f ./dependpkg/safedog.csf /etc/safedog/sdcc")
        fPopen("cp -a -f ./dependpkg/safedog_user.psf /etc/safedog/sdcc")
        fPopen("cp -a -f ./dependpkg/safedog_normal.psf /etc/safedog/sdcc")
        fPopen("cp -a -f ./dependpkg/sdcc.log.cfg /etc/safedog/sdcc/conf/")
        fPopen("cp -a -f ./dependpkg/SafedogIDCType.conf /etc/safedog/sdcc/")
        fPopen("cp -a -f ./dependpkg/updatehelper.conf /etc/safedog/sdcc/conf/")
        fPopen("cp -a -f ./dependpkg/udcenter_options.conf /etc/safedog/sdcc/conf/")
        
        fPopen("cp -a -f ./dependpkg/sdwebdir.conf /etc/safedog/sdcc/plugin/plugin_wrapper.d/")
        fPopen("cp -a -f ./dependpkg/sdwebdir.log.cfg /etc/safedog/server/conf/")

        fPopen("cp -a -f ./dependpkg/sdrtdefendupdate.log.cfg /etc/safedog/server/conf/")

        fPopen("cp -a -f ./dependpkg/script/sdccboot  /etc/init.d/")
        if(iSelect == 5):
            fPopen("rm -rf /etc/init.d/rc2.d/S99sdccboot")
            fPopen("rm -rf /etc/init.d/rc3.d/S99sdccboot")
            fPopen("rm -rf /etc/init.d/rc4.d/S99sdccboot")
            fPopen("rm -rf /etc/init.d/rc5.d/S99sdccboot")
            fPopen("ln -s -f /etc/init.d/sdccboot /etc/init.d/rc2.d/S99sdccboot")
            fPopen("ln -s -f /etc/init.d/sdccboot /etc/init.d/rc3.d/S99sdccboot")
            fPopen("ln -s -f /etc/init.d/sdccboot /etc/init.d/rc4.d/S99sdccboot")
            fPopen("ln -s -f /etc/init.d/sdccboot /etc/init.d/rc5.d/S99sdccboot")
        else:
            fPopen("rm -rf /etc/rc2.d/S99sdccboot")
            fPopen("rm -rf /etc/rc3.d/S99sdccboot")
            fPopen("rm -rf /etc/rc4.d/S99sdccboot")
            fPopen("rm -rf /etc/rc5.d/S99sdccboot")
            fPopen("ln -s -f /etc/init.d/sdccboot /etc/rc2.d/S99sdccboot")
            fPopen("ln -s -f /etc/init.d/sdccboot /etc/rc3.d/S99sdccboot")
            fPopen("ln -s -f /etc/init.d/sdccboot /etc/rc4.d/S99sdccboot")
            fPopen("ln -s -f /etc/init.d/sdccboot /etc/rc5.d/S99sdccboot")

        fPopen("cp -a -f ./dependpkg/script/udboot  /etc/init.d/")
        fPopen("rm -rf /etc/rc2.d/S99udboot")
        fPopen("rm -rf /etc/rc3.d/S99udboot")
        fPopen("rm -rf /etc/rc4.d/S99udboot")
        fPopen("rm -rf /etc/rc5.d/S99udboot")

        fPopen("chmod -R 700 /etc/safedog/libs/sdcc")
        fPopen("chmod -R 700 /etc/safedog")
    
    if (gd.bPrivate == 1) and (gd.bSilent == 0):
        post_install_common_do()

    fPopen("sdmonitor")
    return

def install_apache(now_step,all_step,show_type,install_type):
    global gd
    sitedogname="safedogwz_linux"+str(gd.longbit)
    os.system("chmod +x ./"+sitedogname+"/install.sh")
    os.chdir("./"+sitedogname) 
    os.system("./install.sh "+str(now_step)+" "+str(all_step)+" "+str(show_type)+" "+str(install_type))
    os.chdir("..")
    
def install_nginx(now_step,all_step,show_type,install_type):
    global gd
    nginxdirname="safedog_nginx_linux"+str(gd.longbit)
    os.system("chmod +x ./"+nginxdirname+"/install.sh")
    os.chdir("./"+nginxdirname) 
    os.system("./install.sh "+str(now_step)+" "+str(all_step)+" "+str(show_type)+" "+str(install_type))
    os.chdir("..")
    
def install_tomcat(now_step,all_step,show_type,install_type):
    global gd
    tomcatdirname="safedog_tomcat_linux"+str(gd.longbit)
    os.system("chmod +x ./"+tomcatdirname+"/install.py")
    os.chdir("./"+tomcatdirname)
    os.system("./install.py "+str(now_step)+" "+str(all_step)+" "+str(show_type)+" "+str(install_type))
    os.chdir("..")
    
def Usage():
    global gd
    print "Usage:./install.py [-A|-s|-a|-n|-h]"
    print "-A : install ALL Defense Module"
    print "-s : install Server Defense Module"
    print "-a : install Apache Defense Module"
    print "-n : install Nginx Defense Module"
    print "-t : install Tomcat Defense Module"
    print "-h : print this help"
    
def getPacketType():
    packetType=""
    packetType,sErr= fPopen("cat ./packetType |awk 'NR==1'")
    if(len(packetType) <= 0):
            return 1
    if(packetType[0:6] == "server"):
            return 1
    if(packetType[0:6] == "apache"):
            return 2
    if(packetType[0:5] == "nginx"):
            return 3
    return 1

def getCheckWebInstall():
    if(not os.path.exists("/etc/nginxsd.conf") and os.path.exists("/etc/apachesd.conf")):
        return "apache"
    if(os.path.exists("/etc/nginxsd.conf") and not os.path.exists("/etc/apachesd.conf")):
        return "nginx"
    if(os.path.exists("/etc/nginxsd.conf") and os.path.exists("/etc/apachesd.conf")):
        return "web_all"
    return "web_no"

def getSelectWebInstall():
    if (gd.bSilent == 1):
        return "web_no"
    try:
        select=raw_input("\n1. Select Install Apache.  2. Nginx defense module(enter Ctrl-C to exit). input 1 or 2: ")
    except KeyboardInterrupt:   
        print("\nCancel install web defense module!")
        return "web_no"
    if(not len(select)==1):
        print("\nInput error, cancel install web defense module!")
        return "web_no"
    try:
        sNum = int(select)
    except(ValueError):
        print("\nInput error, cancel install web defense module!")
        return "web_no"
    if (sNum == 1):
        return "apache"
    elif (sNum == 2):
        return "nginx"
    else:
        print("\nInput error, cancel install web defense module!")
        return "web_no"

def getSelectType():
    webInstall = getCheckWebInstall()
    if(webInstall == "apache" or webInstall == "nginx"):
        return webInstall
    if(webInstall == "web_all"):
        return getSelectWebInstall()
        
    fPopen("chmod +x ./check_webserver.sh")
    check_server,Err = fPopen("./check_webserver.sh")

    if(check_server[0:1] == "1"):
        return "apache";
    if(check_server[0:1] == "2"):
        return "nginx";
    if(check_server[0:1] == "3"):
        return getSelectWebInstall() 
    return "web_no"

def uninstall_common():
    global gd
    gd.arrOsDes=['','ubuntu','centos','fedora','hat','suse','asianux','debian','else']

    sOut,sErr = fPopen("cat /etc/issue")
    sIssueRes = sOut.lower()
    iSelect = 0
    idxArrOs = 1
    while(idxArrOs <= 7):
        if(sIssueRes.find(gd.arrOsDes[idxArrOs]) != -1):
            iSelect = idxArrOs
            break
        else:
            idxArrOs += 1

    stop_server()
    fPopen("rm -rf /etc/safedog")
    fPopen("rm -rf /etc/safedog/libs/safedog")
    fPopen("rm -rf /etc/safedog/libs/sdcommon")
    fPopen("rm -rf /etc/safedog/libs/sdcc")
    fPopen("rm -rf /etc/cloudhelper")
    fPopen("rm -rf /etc/init.d/sdccboot")

    if(iSelect == 5):
        fPopen("rm -rf /etc/init.d/rc2.d/S99sdccboot")
        fPopen("rm -rf /etc/init.d/rc3.d/S99sdccboot")
        fPopen("rm -rf /etc/init.d/rc4.d/S99sdccboot")
        fPopen("rm -rf /etc/init.d/rc5.d/S99sdccboot")
    else:
        fPopen("rm -rf /etc/rc2.d/S99sdccboot")
        fPopen("rm -rf /etc/rc3.d/S99sdccboot")
        fPopen("rm -rf /etc/rc4.d/S99sdccboot")
        fPopen("rm -rf /etc/rc5.d/S99sdccboot")
    fPopen("rm -rf /etc/safedog/sdcc/bin/sdcc")
    fPopen("rm -rf /usr/bin/sdcc")
    fPopen("rm -rf /etc/safedog/sdcc/script/runsdcc")
    fPopen("rm -rf /usr/bin/runsdcc")
    fPopen("rm -rf /etc/safedog/sdcc/script/sdccboot")
    fPopen("rm -rf /usr/bin/sdccboot")
    fPopen("rm -rf /etc/safedog/logs/sdcc.log")
    fPopen("killall udpro>/dev/null 2>&1")
    fPopen("rm -f /etc/rc2.d/S99udboot")
    fPopen("rm -f /etc/rc3.d/S99udboot")
    fPopen("rm -f /etc/rc4.d/S99udboot")
    fPopen("rm -f /etc/rc5.d/S99udboot")
    fPopen("rm -f /etc/init.d/udboot")
    fPopen("rm -f /etc/safedog/sdcc/script/udboot")
    fPopen("rm -f /usr/bin/udboot")
    fPopen("rm -f /etc/safedog/sdcc/bin/udcenter")
    fPopen("rm -f /usr/bin/udcenter")
    fPopen("rm -f /etc/safedog/sdcc/bin/udpro")
    fPopen("rm -f /usr/bin/udpro")
    fPopen("rm -f /etc/safedog/sdcc/bin/sdalarm")
    fPopen("rm -f /usr/bin/sdalarm")
    fPopen("rm -f /etc/safedog/server/script/sdsetos")
    fPopen("rm -f /usr/bin/sdsetos")
    fPopen("rm -f /etc/safedog/script/safedog_uninstall")
    fPopen("rm -f /usr/bin/safedog_uninstall")
    fPopen("rm -rf /etc/sd_uninstall/")
    fPopen("rmmod sddev")
    
def stop_old_server():
    #print("start stop_old_server")
    fPopen("rmmod sddev")
    fPopen("sdmonitor -QUIT")
    fPopen("sleep 3")
    fPopen("killall -9 sdmonitor>/dev/null 2>&1")
    fPopen("killall sdcc >/dev/null 2>&1")
    fPopen("killall udcenter >/dev/null 2>&1")
    fPopen("sdcmd exit >/dev/null 2>&1 &")
    fPopen("killall sdcmd >/dev/null 2>&1")
    fPopen("killall sdsvrd >/dev/null 2>&1")
    fPopen("killall sduibin >/dev/null 2>&1")
    #print("end stop_old_server")
    return
    
def backup_user_data():
    #print("start backup_user_data")
    fPopen("rm -rf /tmp/safedog_back")
    fPopen("cp -rf /etc/safedog /tmp/safedog_back")
    
    fPopen("rm -rf /tmp/safedog_logs_back")
    fPopen("mkdir -p /tmp/safedog_logs_back")
    fPopen("cp -f /var/log/sd*.log /tmp/safedog_logs_back")
    #print("end backup_user_data")
    return

def uninstall_old_server():
    #print("start uninstall_old_server")
    arrOsDes=['','ubuntu','centos','fedora','hat','suse','asianux','else']
    if(os.path.exists("/usr/bin/uduninstall") == False):
        print("old version had uninstall")
        return
        
    sOut,sErr = fPopen("cat /etc/issue")
    sIssueRes = sOut.lower()
    iSelect = 0
    idxArrOs = 1
    while (idxArrOs <= 6):
        if (sIssueRes.find(arrOsDes[idxArrOs]) != -1):
            iSelect = idxArrOs
            break
        else:
            idxArrOs += 1
    
    arrCmds = []
    arrLnxCmds = []
    arrSuseCmds = []
    
    #arrLnxCmds.append("rm -rf /etc/rc2.d/S99sdboot")
    #arrLnxCmds.append("rm -rf /etc/rc3.d/S99sdboot")
    #arrLnxCmds.append("rm -rf /etc/rc4.d/S99sdboot")
    #arrLnxCmds.append("rm -rf /etc/rc5.d/S99sdboot")
    
    #arrSuseCmds.append("rm -rf /etc/rc.d/rc2.d/S99sdboot")
    #arrSuseCmds.append("rm -rf /etc/rc.d/rc3.d/S99sdboot")
    #arrSuseCmds.append("rm -rf /etc/rc.d/rc4.d/S99sdboot")
    #arrSuseCmds.append("rm -rf /etc/rc.d/rc5.d/S99sdboot")
    
    arrCmds.append("rm -rf /etc/init.d/safedog")
    #arrCmds.append("rm -rf /etc/init.d/sdboot")
    arrCmds.append("rm -rf /usr/bin/safedog")
    #arrCmds.append("rm -rf /usr/bin/sdboot")
    arrCmds.append("rm -rf /usr/bin/sdstart")
    arrCmds.append("rm -rf /usr/bin/sdsvrd")
    arrCmds.append("rm -rf /usr/bin/sdcmd")
    arrCmds.append("rm -rf /usr/bin/sdtest")
    arrCmds.append("rm -rf /usr/bin/sdui")
    arrCmds.append("rm -rf /usr/bin/sduibin")
    arrCmds.append("rm -rf /usr/bin/sdcloud")
    arrCmds.append("rm -rf /usr/bin/udinstall")
    
    if(gd.longbit == 32):
        arrCmds.append("uduninstall NF-7400L")
    else:
        arrCmds.append("uduninstall NF-7400L64")

    arrCmds.append("rm -rf /usr/bin/uduninstall")
    
    if (os.system("which sdacm 1>/dev/null 2>&1") != 0):
        arrCmds.append("rm -rf /usr/lib/safedog")
        arrCmds.append("rm -rf /usr/lib/sdcc")
        arrCmds.append("rm -rf /etc/init.d/sdccboot")
        arrCmds.append("rm -rf /etc/rc2.d/S99sdccboot")
        arrCmds.append("rm -rf /etc/rc3.d/S99sdccboot")
        arrCmds.append("rm -rf /etc/rc4.d/S99sdccboot")
        arrCmds.append("rm -rf /etc/rc5.d/S99sdccboot")
        arrCmds.append("rm -f /usr/bin/sdcc")
        arrCmds.append("rm -f /usr/bin/sdmonitor")
        #arrCmds.append("rm -f /usr/bin/sd_autoexmn")
        arrCmds.append("rm -f /usr/bin/runsdcc")
        arrCmds.append("rm -f /usr/bin/sdccboot")

        #uninstall init.d
        arrLnxCmds.append("rm -f /etc/rc2.d/S99udboot")
        arrLnxCmds.append("rm -f /etc/rc3.d/S99udboot")
        arrLnxCmds.append("rm -f /etc/rc4.d/S99udboot")
        arrLnxCmds.append("rm -f /etc/rc5.d/S99udboot")

        arrSuseCmds.append("rm -rf /etc/rc.d/rc2.d/S99udboot");
        arrSuseCmds.append("rm -rf /etc/rc.d/rc3.d/S99udboot");
        arrSuseCmds.append("rm -rf /etc/rc.d/rc4.d/S99udboot");
        arrSuseCmds.append("rm -rf /etc/rc.d/rc5.d/S99udboot");
        #end
        
        arrCmds.append("rm -f /etc/init.d/udboot")
        arrCmds.append("rm -f /usr/bin/udboot")
        arrCmds.append("rm -f /usr/bin/udcenter")
        arrCmds.append("rm -f /usr/bin/udpro")
        #arrCmds.append("rm -f /usr/bin/sdalarm")
        arrCmds.append("rm -f /usr/bin/sdsetos")
    else:
        #arrCmds.append("rm -f /usr/bin/sdalarm")
        arrCmds.append("rm -f /usr/bin/sdsetos")
        
        for sCmd in arrCmds:
            sOut,sErr=fPopen(sCmd)
            if(len(sOut) > 0):
                print(sOut)
            if(len(sErr) > 0):
                print(sErr)
                
        if(iSelect != 5):   
            for sLnxCmd in arrLnxCmds:
                sOut,sErr=fPopen(sLnxCmd)
                if(len(sOut) > 0):
                    print(sOut)
                if(len(sErr) > 0):
                    print(sErr)
        else:
            for sSuseCmd in arrSuseCmds:
                sOut,sErr=fPopen(sSuseCmd)
                if(len(sOut) > 0):
                    print(sOut)
                if(len(sErr) > 0):
                    print(sErr)
                    
    fPopen("rm -rf /etc/cloudhelper");
    fPopen("rm -rf /etc/safedog")
    fPopen("rm -rf /usr/lib/safedog")
    fPopen("rm -rf /usr/lib/sdcc")
    fPopen("rm -rf /etc/init.d/sdccboot")
    fPopen("rm -rf /etc/rc2.d/S99sdccboot")
    fPopen("rm -rf /etc/rc3.d/S99sdccboot")
    fPopen("rm -rf /etc/rc4.d/S99sdccboot")
    fPopen("rm -rf /etc/rc5.d/S99sdccboot")
    fPopen("rm -rf /usr/bin/sdcc")
    fPopen("rm -rf /usr/bin/sdmonitor")
    #fPopen("rm -rf /usr/bin/sd_autoexmn");
    fPopen("rm -rf /usr/bin/runsdcc")
    fPopen("rm -rf /usr/bin/sdccboot")
    fPopen("rm -f /etc/rc2.d/S99udboot")
    fPopen("rm -f /etc/rc3.d/S99udboot")
    fPopen("rm -f /etc/rc4.d/S99udboot")
    fPopen("rm -f /etc/rc5.d/S99udboot")
    fPopen("rm -f /etc/init.d/udboo")
    fPopen("rm -f /usr/bin/udboot")
    fPopen("rm -f /usr/bin/udcenter")
    fPopen("rm -f /usr/bin/udpro")
    fPopen("rm -f /usr/bin/sdalarm")
    fPopen("rm -f /usr/bin/sdsetos")
    fPopen("rm -f /usr/bin/safedog_uninstall")
    fPopen("rm -f /usr/bin/sdmonitor")
    fPopen("rmmod sddev")
    fPopen("rm -f /usr/bin/SDDownload")
    fPopen("rm -rf /etc/sd_uninstall/")
    fPopen("rm -f /etc/sdinfo.conf")
    fPopen("rm -f /etc/udcenter.conf")
    fPopen("rm -f /var/log/sd*.log")
    #print("end uninstall_old_server")
    return
    
def uninstall_old_common():
    #print("start uninstall_old_common")
    fPopen("rm -rf /usr/lib/sdcommon")
    #print("end uninstall_old_common")
    
def recovery_user_data():
    #print("start recovery_user_data")
    old_back_dir = "/tmp/safedog_back"
    old_logs_back_dir = "/tmp/safedog_logs_back"
    
    new_server_dir = "/etc/safedog/server"
    new_sdcc_dir = "/etc/safedog/sdcc"
    new_logs_dir = "/etc/safedog/logs"
    
    use_new_file = []
    use_new_file.append("rootkit_files.dat")
    use_new_file.append("weak_dic.dat")
    use_new_file.append("rootkit_trojans.dat")
    use_new_file.append("startup.dat")
    use_new_file.append("WeakPassword.dat")

    #backup new version file
    for file in use_new_file:
        fPopen("rm -f " + old_back_dir + "/examine/" + file)
        fPopen("cp -f " + new_server_dir + "/examine/" + file + " " + old_back_dir + "/examine/")
    
    fPopen("rm -rf " + new_server_dir + "/backup")
    fPopen("cp -rf " + old_back_dir + "/backup " + new_server_dir + "/backup/")
    
    fPopen("rm -rf " + new_server_dir + "/kernelsafedog")
    fPopen("cp -rf " + old_back_dir + "/KernelSafedog " + new_server_dir + "/kernelsafedog/")
    
    old_back_examine_dir = old_back_dir + "/examine/"
    for file in os.listdir(old_back_examine_dir):
        source_file = old_back_examine_dir + "/" + file
        target_file = new_server_dir + "/examine/" + file
        if os.path.exists(target_file):     
            fPopen("rm -rf " + target_file)
        fPopen("cp -rf " + source_file + " " + target_file)
    
    old_back_conf_dir = old_back_dir + "/conf/"
    for file in os.listdir(old_back_conf_dir):
        source_file = old_back_conf_dir + "/" + file
        target_file = new_server_dir + "/conf/" + file
        if os.path.exists(target_file):     
            fPopen("rm -rf " + target_file)
        fPopen("cp -rf " + source_file + " " + target_file)
    
    old_back_monitor_dir = old_back_dir + "/monitor/"
    for file in os.listdir(old_back_monitor_dir):
        source_file = old_back_monitor_dir + "/" + file
        target_file = new_server_dir + "/monitor/" + file
        if os.path.exists(target_file):
            fPopen("rm -rf " + target_file)
        fPopen("cp -rf " + source_file + " " + target_file)
    
    for file in os.listdir(old_back_dir):
        if not (file.endswith(".conf") or file.endswith(".dat")) or file == "srvcloud.conf":
            continue
        source_file = old_back_dir + "/" + file
        target_file = new_server_dir + "/conf/" + file
        if os.path.exists(target_file): 
            fPopen("rm -rf " + target_file)
        fPopen("cp -rf " + source_file + " " + target_file)

    fPopen("cp -f " + old_back_dir + "/safedog_user.psf " + new_sdcc_dir)
    fPopen("cp -f " + old_back_dir + "/safedog_normal.psf " + new_sdcc_dir)
    fPopen("cp -f " + old_logs_back_dir + "/*.log" + new_logs_dir)
    
    # delete backup dir
    #fPopen("rm -rf " + old_back_dir)
    #fPopen("rm -rf " + old_logs_back_dir)
    #print("end recovery_user_data")
    return
 
def check_ip(ip):
     pattern = r"\b(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[    0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][    0-9]?)\b"
     if re.match(pattern, ip):
         return True
     else:
         return False


def indent(elem, level=0):
    i = "\n" + level*"    "
    if len(elem):
        if not elem.text or not elem.text.strip():
            elem.text = i + "    "
        if not elem.tail or not elem.tail.strip():
            elem.tail = i
        for elem in elem:
            indent(elem, level+1)
        if not elem.tail or not elem.tail.strip():
            elem.tail = i
    else:
        if level and (not elem.tail or not elem.tail.strip()):
            elem.tail = i

def redirect_hosts(server_ip, askpass):
    if askpass == "1":
        input_ip = raw_input("\n  Please enter the server ip [%s]:"%server_ip)

        if (check_ip(input_ip) == False):
            print("  will use default ip[%s]"%server_ip)
            input_ip = server_ip
    else:
        input_ip = server_ip

    server_tup = ('scancloud.safedog.cn', 'sft.safedog.cn', 'cdnspeed.safedog.cn', 'passport.safedog.cn', 'soft.safedog.cn', 'nginx.safedog.cn', 'kernel.safedog.cn', 'down.safedog.cn', 'scan-cloud.safedog.cn', 'patch.safedog.cn', 'patchfile.safedog.cn', 'client-server.safedog.cn', 'client-pc.safedog.cn', 'fuyun.safedog.cn', 'cloud.safedog.cn','passport.safedog.cn', 'www.safedog.cn', 'config.safedog.cn', 'client-server1.safedog.cn', 'client-server2.safedog.cn', 'client-server3.safedog.cn', 'client-server4.safedog.cn', 'client-server5.safedog.cn')
    dataEle = ET.Element("data")
    dataEle.attrib["version"] = "0.0"
    for i in range(len(server_tup)):
        domainEle = ET.SubElement(dataEle, "domain")
        domainEle.set("ip", input_ip)
        domainEle.set("name", server_tup[i])

    indent(dataEle)
    dataTree = ET.ElementTree(dataEle)
    try:
        dataTree.write("/etc/safedog/sdcc/conf/SdHost.conf")
    except IOError:
        print 'write fail'

def post_install_common_do():
    cf = ConfigParser.ConfigParser()
    cf.read("./dependpkg/install_options.conf")

    try:
        server_ip = cf.get("general", "serverip")
        askpass = cf.get("general", "askpass")
    except (ConfigParser.NoSectionError, ConfigParser.NoOptionError):
        pass
    else:
        if (check_ip(server_ip) == True):
            redirect_hosts(server_ip, askpass)
        else:
            print("the server ip in install_options.conf is not correct")
  
if __name__ == "__main__":
    main()
    sys.exit(0)

