#!/usr/bin/env python2
exit()
"""
    Check to make sure that clamd and other daemons  are active

    Copyright  Afrihost.com (PTY) Ltd 2004
    Original file by: Ed Pascoe <ed@pascoe.co.za>
"""
__author__  = "Ed Pascoe <ed@pascoe.co.za>"
__credits__ = "Afrihost.com -- The best webhosting. Ever."

#remote_host="blofeld.co.za"

import os.path, sys, dircache, os,signal,time
import types
if __name__=='__main__': sys.path.append(os.path.dirname(os.path.realpath(sys.argv[0]))+'/../pylib')
import timeoutsocket
import socket
timeoutsocket.setDefaultSocketTimeout(10)

def psfind(psname):
    pslist=[]
    for f in dircache.listdir("/proc"):
        try: fi=int(f)  #I only want to look at processes
        except ValueError: continue 
        try:
            if os.readlink(os.path.join("/proc",f,"exe")).find(psname) > -1:
                pslist.append(fi)
        except OSError: continue
        except Exception,e: 
            print "Skipping %s ---> %s " % (f,e)
            continue
    return pslist
def killGroup(pslist,signal):
    for ps in pslist: 
        try: os.kill(ps,signal)
        except Exception,e:
            print "Failure to kill %s --> %s " % (ps,e)
            continue
def restartServer(estr):
    global startcmd,searchcmd
    print time.strftime("%Y-%m-%d %H:%M:%S") , "Restarting server", estr
    pslist= psfind(searchcmd);
    killGroup(pslist,signal.SIGTERM)
    time.sleep(3) #Give them a chance to die softly
    killGroup(pslist,signal.SIGKILL) #Kill -9 them all and let root sort it out :)
    os.system(startcmd)

def monitorserver(processname,restartcmd="",testfile="", removefile=""):
    """Tests for processname, and if not runing restarts the daemon
     if removefile is a string or and array will remove every filename before running restartcmd
     if restartcmd is blank will use processname instead
     if testfile does not exist will not do tests (if blank uses restartcmd)
    """
    if not restartcmd:  restartcmd = processname
    if not testfile:  testfile = restartcmd
    #Incase package do
    if not os.path.exists(testfile): return

    if not psfind(processname):
        print processname,"has died restarting"
        if removefile:
            if type(removefile)== types.StringType: removefile=[removefile]
            for f in removefile:
                print "Removing " , f
                try: os.unlink(f)
                except: pass

        os.system(restartcmd)

def cppopcheck():
    remote_host="127.0.0.1"
    remote_port=110
    searchcmd="/usr/local/cpanel/bin/cppop"
    startcmd="/usr/local/cpanel/bin/cppop"
    try: #See if pop server is active
        sock=socket.socket(socket.AF_INET, socket.SOCK_STREAM)
        sock.connect((remote_host, remote_port))
        d= sock.recv(1024)
        if d.upper().find("+OK") != 0: #Make sure we get correct connection
            raise Exception,"Server response incorrect"
        sock.send("quit\r\n")
        sock.recv(1024)
        sock.close
    except Exception,e:
        restartServer(str(e))    
 
cppopcheck()
monitorserver("/usr/sbin/clamd",removefile="/var/run/clamav/clamd")
monitorserver("/usr/sbin/atd")

