#!/usr/bin/env python

import os,sys,time,socket,threading,copy,StringIO,cPickle,subprocess,fcntl,struct,signal,shutil,base64

class cGlobalData:
    pass
    
gd=cGlobalData()
gd.isTest = False
gd.isUninstallApache = False 
gd.isUninstallSafedog = False
gd.isUninstallNginx = False
gd.packetType=1


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

def Usage():
#   global gd
    print "Usage:./uninstall.py [-A|-a|-n|-s|-h]"
    print "-A : uninstall all Defense Module of Safedog"
    print "-s : uninstall Server Defense Module"
#   if(not gd.packetType == 3):
    print "-a : uninstall Apache Defense Module"
#   if(not gd.packetType ==2):
    print "-n : uninstall Nginx Defense Module"
    print "-h : print this help"                                                
                                                                                
def print_resault(buf,type):
    print_len=94
    lens=len(buf)
    if(type == 0):
        print(buf),
        print("\033[1;32;10m"),
        print(" ".ljust(print_len-lens)+"[ok]"), 
    elif(type == 1):
        print(buf),
        print("\033[1;33;10m"),
        print(" ".ljust(print_len-lens)+"[warn]"), 
    elif(type == 2):
        print(buf),
        print("\033[1;31;10m"),
        print(" ".ljust(print_len-lens)+"[error]"), 
    elif(type == 3):
        print("\033[1;32;10m"),
        print(buf),
    elif(type == 4):
        print("\033[1;33;10m"),
        print(buf),
    print("\033[0m")

def uninstall_server(showType):
    if(showType==1):
        select=raw_input("Do you uninstall Server Defense Module?[y/N]:")
        if(not select == "y" and  not select == "Y"):
            return 
    if(os.path.exists("/usr/bin/uduninstall")):
        initGD()
        print_resault("Collecting setup information",0)
        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
        for sCmd in gd.arrCmds:
        #print sCmd
            sOut,sErr=fPopen(sCmd)
            if(len(sOut) > 0):
                print sOut
            if(len(sErr) > 0):
                print sErr
        if(iSelect != 5):   
            for sLnxCmd in gd.arrLnxCmds:
                sOut,sErr=fPopen(sLnxCmd)
                if(len(sOut) > 0):
                    print sOut
                if(len(sErr) > 0):
                    print sErr
        else:
            for sSuseCmd in gd.arrSuseCmds:
                sOut,sErr=fPopen(sSuseCmd)
                if(len(sOut) > 0):
                    print sOut
                if(len(sErr) > 0):
                    print sErr          
        print_resault("Uninstall Server Defense Module",0)
    else:
        print"Server Defense Module is not installed"

def uninstall_apache(showType):
    global gd
    sitedogname="safedogwz_linux"+str(gd.iBit)
    os.system("chmod +x ./"+sitedogname+"/uninstall.sh")
    os.chdir("./"+sitedogname) 
    os.system("./uninstall.sh 0 "+str(showType))
    os.chdir("..")

def uninstall_nginx(showType):
    global gd
    nginxdirname="safedog_nginx_linux"+str(gd.iBit)
    os.system("chmod +x ./"+nginxdirname+"/uninstall.sh")
    os.chdir("./"+nginxdirname) 
    os.system("./uninstall.sh  0 "+str(showType))
    os.chdir("..")
    
def uninstall_tomcat(showType):
    global gd
    tomcatdirname="safedog_tomcat_linux"+str(gd.iBit)
    os.system("chmod +x ./"+tomcatdirname+"/uninstall.py")
    os.chdir("./"+tomcatdirname) 
    os.system("./uninstall.py  0 "+str(showType))
    os.chdir("..")  

def uninstall_common():
    stop_server()
    fPopen("rm -rf /etc/cloudhelper")
    fPopen("rm -rf /etc/safedog")
    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 -f /usr/bin/sdcc")
    fPopen("rm -f /usr/bin/sdmonitor")
    fPopen("rm -f /usr/bin/sd_autoexmn");
    fPopen("rm -f /usr/bin/runsdcc")
    fPopen("rm -f /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/udboot")
    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 -rf /etc/sdinfo.conf")
    fPopen("rm -rf /etc/udcenter.conf")
    fPopen("rm -rf /sys/fs/cgroup/cpu/safedog")
    fPopen("rm -rf /cgroup/cpu/safedog")

def stop_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")

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 main():
    global gd
    showType=0
    stepFollow=[]
    funcSets={"server":uninstall_server,"apache":uninstall_apache,"nginx":uninstall_nginx,"tomcat":uninstall_tomcat}
        
    gd.iBit=0
    sOut,sErr = fPopen("getconf LONG_BIT")
    if( int(sOut) == 32):
        gd.iBit=32
    else:
        gd.iBit=64
        
    #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):
        print("\033[1;32;10m Tips : Execute install.py directly, please.\033[0m" + "\n  Ready to install version:2.8.x \n   Installed version:" + sOut)
        return

    for i in range(1, len(sys.argv)):
        if (sys.argv[i] == "-s"):
            stepFollow.append("server")
        elif (sys.argv[i] == "-a"):
            stepFollow.append("apache")
        elif (sys.argv[i] == "-n"):
            stepFollow.append("nginx")
        elif (sys.argv[i] == "-t"):
            stepFollow.append("tomcat")
            
    stop_server()
    for key in stepFollow:
        funcSets[key](0)

    uninstall_common()
    print_resault("Uninstall Common Module", 0)
    print("Uninstall completely!")
    
    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 ClearHandleDbCmd():
    cmd = "[{\"dbName\":\"handlecache\",\"tableName\":\"VirusHandleIsolationInfo\",\"action\":\"batchDelete\",\"records\":[]}]"
    cmdbase = base64.b64encode(cmd) 
    currtime = time.strftime("%Y-%m-%d %H:%M:%S",  time.localtime(time.time()))
    timebase = base64.b64encode(currtime) 
    return ("sdalarm -r dbOperation %s %s"%(timebase,cmdbase))


def initGD():
    global gd
    
    gd.arrCmds=[]
    gd.arrLnxCmds=[]
    gd.arrSuseCmds=[]

    gd.arrOs=['','ubuntu','centos','fedora','rhel','suse','asianux','debian','else']
    gd.arrOsDes=['','ubuntu','centos','fedora','hat','suse','asianux','debian', 'else']

    if( os.path.isfile("/etc/safedog/server/conf/handlecache.db") or 
        (os.path.isfile("/etc/safedog/server/examine/isolation_list.conf") 
        and os.path.isdir("/etc/safedog/server/examine/isolation_files") 
        and len(os.listdir("/etc/safedog/server/examine/isolation_files")) > 0)):
        r = raw_input("Would you like to backup the files of isolation?[Y/n]:")
        if(r == "N" or r== "n" ):
            print "remove files of isolation "
            gd.arrCmds.append(ClearHandleDbCmd())
        else :
            gd.arrCmds.append("mkdir -p /etc/safedog/server/backup/isolation_info_bak >/dev/null 2>&1");
            gd.arrCmds.append("mv /etc/safedog/server/examine/isolation_list.conf /etc/safedog/server/backup/isolation_info_bak/ >/dev/null 2>&1");
            gd.arrCmds.append("mv /etc/safedog/server/examine/isolation_files  /etc/safedog/server/backup/isolation_info_bak/ >/dev/null 2>&1");
            gd.arrCmds.append("mv /etc/safedog/server/conf/handlecache.db  /etc/safedog/server/backup/isolation_info_bak/ >/dev/null 2>&1");

    #gd.arrCmds.append("killall sduibin >/dev/null 2>&1")
#gd.arrCmds.append("sdcmd exit >/dev/null 2>&1 &")
#   gd.arrCmds.append("sleep 2")
#   gd.arrCmds.append("killall sdsvrd >/dev/null 2>&1")

    #uninstall init.d
    #gd.arrLnxCmds.append("rm -rf /etc/rc2.d/S99sdboot")
    #gd.arrLnxCmds.append("rm -rf /etc/rc3.d/S99sdboot")
    #gd.arrLnxCmds.append("rm -rf /etc/rc4.d/S99sdboot")
    #gd.arrLnxCmds.append("rm -rf /etc/rc5.d/S99sdboot")

    #gd.arrSuseCmds.append("rm -rf /etc/rc.d/rc2.d/S99sdboot")
    #gd.arrSuseCmds.append("rm -rf /etc/rc.d/rc3.d/S99sdboot")
    #gd.arrSuseCmds.append("rm -rf /etc/rc.d/rc4.d/S99sdboot")
    #gd.arrSuseCmds.append("rm -rf /etc/rc.d/rc5.d/S99sdboot")
    #end
    
    gd.arrCmds.append("rm -rf /etc/init.d/safedog")
    #gd.arrCmds.append("rm -rf /etc/init.d/sdboot")
    gd.arrCmds.append("rm -rf /usr/bin/safedog")
    gd.arrCmds.append("rm -rf /etc/safedog/server/script/safedog")
    #gd.arrCmds.append("rm -rf /usr/bin/sdboot")
    #gd.arrCmds.append("rm -rf /etc/safedog/server/script/sdboot")
    gd.arrCmds.append("rm -rf /usr/bin/sdstart")
    gd.arrCmds.append("rm -rf /etc/safedog/server/script/sdstart")
    gd.arrCmds.append("rm -rf /usr/bin/sdsvrd")
    gd.arrCmds.append("rm -rf /etc/safedog/server/bin/sdsvrd")
    gd.arrCmds.append("rm -rf /usr/bin/sdwebdir")
    gd.arrCmds.append("rm -rf /etc/safedog/server/bin/sdwebdir")
    gd.arrCmds.append("rm -rf /usr/bin/sdrtdefendupdate")
    gd.arrCmds.append("rm -rf /etc/safedog/server/bin/sdrtdefendupdate")
    gd.arrCmds.append("rm -rf /usr/bin/sdcmd")
    gd.arrCmds.append("rm -rf /etc/safedog/server/bin/sdcmd")
    gd.arrCmds.append("rm -rf /usr/bin/sdtest")
    gd.arrCmds.append("rm -rf /etc/safedog/server/bin/sdtest")  
    gd.arrCmds.append("rm -rf /usr/bin/sdui")
    gd.arrCmds.append("rm -rf /etc/safedog/server/script/sdui")
    gd.arrCmds.append("rm -rf /usr/bin/sduibin")
    gd.arrCmds.append("rm -rf /etc/safedog/server/bin/sduibin")
    gd.arrCmds.append("rm -rf /usr/bin/sdcloud")
    gd.arrCmds.append("rm -rf /etc/safedog/server/bin/sdcloud")
    gd.arrCmds.append("rm -rf /usr/bin/udinstall")
    gd.arrCmds.append("rm -rf /etc/safedog/server/bin/udinstall")
    
    if (gd.isTest ==  True):
        if(gd.iBit == 32):
            gd.arrCmds.append("uduninstall NF-7400L test")
        else:
            gd.arrCmds.append("uduninstall NF-7400L64 test")
    else:
        if(gd.iBit == 32):
            gd.arrCmds.append("uduninstall NF-7400L")
        else:
            gd.arrCmds.append("uduninstall NF-7400L64")

    gd.arrCmds.append("rm -rf /etc/safedog/logs/sdsvrd.log")
    gd.arrCmds.append("rm -rf /etc/safedog/logs/sdcmd.log")
    #gd.arrCmds.append("rm -rf /etc/safedog/logs/sdui.log")
    #gd.arrCmds.append("rm -rf /etc/safedog/logs/newsdui.log")
    gd.arrCmds.append("rm -rf /etc/safedog/logs/sdupdate.log")
    gd.arrCmds.append("rm -rf /etc/safedog/logs/ips.log")
    gd.arrCmds.append("rm -rf /usr/bin/uduninstall")
    gd.arrCmds.append("rm -rf /etc/safedog/server/bin/uduninstall")
    if(os.path.exists("/etc/safedog/server/conf/SafedogIDCType.conf")):
        gd.arrCmds.append("cp -a -f /etc/safedog/server/conf/SafedogIDCType.conf /etc/safedog/server/backup/SafedogIDCType.conf.bak")

    if (os.system("which sdacm 1>/dev/null 2>&1") != 0):
        gd.arrCmds.append("rm -rf /etc/safedog/libs/safedog")
        gd.arrCmds.append("rm -rf /etc/safedog/libs/sdcommon")
        gd.arrCmds.append("rm -rf /etc/safedog/libs/sdcc")
        gd.arrCmds.append("rm -rf /etc/safedog")
        gd.arrCmds.append("rm -rf /etc/init.d/sdccboot")
        gd.arrCmds.append("rm -rf /etc/rc2.d/S99sdccboot")
        gd.arrCmds.append("rm -rf /etc/rc3.d/S99sdccboot")
        gd.arrCmds.append("rm -rf /etc/rc4.d/S99sdccboot")
        gd.arrCmds.append("rm -rf /etc/rc5.d/S99sdccboot")
#       gd.arrCmds.append("killall sdmonitor >/dev/null 2>&1")
#       gd.arrCmds.append("killall sdcc>/dev/null 2>&1")
        gd.arrCmds.append("rm -rf /usr/bin/sdcc")
        gd.arrCmds.append("rm -rf /etc/safedog/sdcc/bin/sdcc")
        gd.arrCmds.append("rm -rf /usr/bin/sdmonitor")
        gd.arrCmds.append("rm -rf /etc/safedog/sdcc/bin/sdmonitor")
        gd.arrCmds.append("rm -rf /usr/bin/sd_autoexmn")
        gd.arrCmds.append("rm -rf /etc/safedog/server/bin/sd_autoexmn")
        gd.arrCmds.append("rm -rf /usr/bin/runsdcc")
        gd.arrCmds.append("rm -rf /etc/safedog/sdcc/script/runsdcc")
        gd.arrCmds.append("rm -rf /usr/bin/sdccboot")
        gd.arrCmds.append("rm -rf /etc/safedog/sdcc/script/sdccboot")       
        gd.arrCmds.append("rm -rf /etc/safedog/logs/sdcc.log")

#       gd.arrCmds.append("killall udcenter>/dev/null 2>&1")
#       gd.arrCmds.append("killall udpro>/dev/null 2>&1")

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

        gd.arrSuseCmds.append("rm -rf /etc/rc.d/rc2.d/S99udboot");
        gd.arrSuseCmds.append("rm -rf /etc/rc.d/rc3.d/S99udboot");
        gd.arrSuseCmds.append("rm -rf /etc/rc.d/rc4.d/S99udboot");
        gd.arrSuseCmds.append("rm -rf /etc/rc.d/rc5.d/S99udboot");
        #end
        
        gd.arrCmds.append("rm -f /etc/init.d/udboot")
        gd.arrCmds.append("rm -f /usr/bin/udboot")
        gd.arrCmds.append("rm -f /etc/safedog/sdcc/script/udboot")
        gd.arrCmds.append("rm -f /usr/bin/udcenter")
        gd.arrCmds.append("rm -f /etc/safedog/sdcc/bin/udcenter")
        gd.arrCmds.append("rm -f /usr/bin/udpro")
        gd.arrCmds.append("rm -f /etc/safedog/sdcc/bin/udpro")      
        gd.arrCmds.append("rm -f /usr/bin/sdalarm")
        gd.arrCmds.append("rm -f /etc/safedog/sdcc/bin/sdalarm")
        gd.arrCmds.append("rm -f /usr/bin/sdsetos")
        gd.arrCmds.append("rm -f /etc/safedog/server/script/sdsetos")
    else:
        gd.arrCmds.append("rm -rf /etc/safedog/server/conf/sdsvrd.conf")
        gd.arrCmds.append("rm -rf /etc/safedog/server/backup/")
        gd.arrCmds.append("rm -rf /etc/safedog/server/conf/")
        gd.arrCmds.append("rm -rf /etc/safedog/server/dmp/")
        gd.arrCmds.append("rm -rf /etc/safedog/server/kernelsafedog/")
        gd.arrCmds.append("rm -rf /etc/safedog/server/monitor/")
        gd.arrCmds.append("rm -rf /etc/safedog/server/script/")
        gd.arrCmds.append("rm -rf /etc/safedog/server/bin/")
        gd.arrCmds.append("rm -rf /etc/safedog/server/examine/")
        gd.arrCmds.append("rm -rf /etc/safedog/server/update/")
        gd.arrCmds.append("rm -rf /etc/safedog/server/")
        gd.arrCmds.append("rm -rf /etc/safedog/sdcc/bin/")
        gd.arrCmds.append("rm -rf /etc/safedog/sdcc/sdcc_dmp/")
        gd.arrCmds.append("rm -rf /etc/safedog/sdcc/plugin/")
        gd.arrCmds.append("rm -rf /etc/safedog/sdcc/script/")
        gd.arrCmds.append("rm -rf /etc/safedog/sdcc/backup/")
        gd.arrCmds.append("rm -rf /etc/safedog/sdcc/conf/")
        gd.arrCmds.append("rm -rf /etc/safedog/sdcc/")
        gd.arrCmds.append("rm -f /usr/bin/sdalarm")
        gd.arrCmds.append("rm -f /usr/bin/sdsetos")

    if (gd.isTest !=  True):
        gd.arrCmds.append("date >> /etc/sduninstall.log")
    return

if __name__ == "__main__":
    main()
    os._exit(0)

