#!/usr/bin/env python

import sys, os, signal, subprocess, shlex,time,atexit

shutdown = False
queue_process = None


def file_pid(name):
    proc1 = subprocess.Popen(shlex.split('ps aux'), stdout=subprocess.PIPE)
    proc2 = subprocess.Popen(shlex.split('grep ' + name), stdin=proc1.stdout, stdout=subprocess.PIPE, stderr=subprocess.PIPE)
    proc3 = subprocess.Popen(shlex.split('awk \'{print $2}\' '), stdin=proc2.stdout, stdout=subprocess.PIPE, stderr=subprocess.PIPE)

    proc1.stdout.close()
    proc2.stdout.close()
    out, err = proc3.communicate()

    lines = out.splitlines()
    pids = []
    for line in lines :
        item = line.strip()
        pid = int(item)
        if pid > 0:
            pids.append(pid)

    if len(pids) > 0 :
        return pids
    else:
        return []


def kill_pid(name):
	print "kill_pid ",name
	cur_pid = os.getpid()
	pids = file_pid(name)
	for pid in pids:
		try:
			if cur_pid != pid:
				os.kill(pid, signal.SIGKILL)
				print 'kill pid=', pid
			else:
				continue
		except OSError, e:
			pass
		except BaseException, be:
			pass
	return


def sig_handler(sig,frame):
	global shutdown
	global queue_process

	frame = None
	if sig == signal.SIGINT:
		shutdown = True
	elif sig == signal.SIGTERM:
		shutdown = True

	if shutdown == True and queue_process != None:
		for proc in queue_process:
			proc.terminate()


class Daemon(object):
	def __init__(self,input='/dev/null',output='/tmp/qwatch.out'):
		self.infile  = input
		self.outfile = output


	def register_handler(self):
		signal.signal(signal.SIGINT,  sig_handler)
		signal.signal(signal.SIGTERM, sig_handler)
		signal.signal(signal.SIGCHLD, sig_handler)

	def daemonize(self):
		try:
			pid = os.fork()
			if pid != 0:
				sys.exit(0)
		except OSError, e:
			sys.stderr.write("fork #1 failed: %d (%s)\n" % (e.errno, e.strerror))
			sys.exit(1)

		os.setsid()
		os.umask(0)

		try:
			pid = os.fork() 
			if pid != 0:
				sys.exit(0)
		except OSError, e: 
			sys.stderr.write("fork #2 failed: %d (%s)\n" % (e.errno, e.strerror))
			sys.exit(1)

		os.close(0)
		os.close(1)
		os.close(2)

		os.open(self.infile,os.O_RDONLY)
		os.open(self.outfile,os.O_WRONLY | os.O_APPEND | os.O_CREAT,0666)
		os.dup(1)
		print "********************************************************"

def mac_sys():
	plat_name = sys.platform
	return plat_name == 'darwin'


def main():
	global queue_process

	kill_pid("qwatch.py")
	kill_pid("crontab.php")

	queue_process = list()

	d = Daemon()
	d.daemonize()
	d.register_handler()

	print "cur_pid =" , os.getpid()

	if mac_sys() :
		cmds = ["php", "./crontab.php", "queue", "index"]
		proc_num = 1
	else:
		cmds = ["/usr/local/php/bin/php", "./crontab.php", "queue", "index"]
		proc_num = 10

	for i in range(0, proc_num):
		subproc = subprocess.Popen(cmds, close_fds=True, stdin=None, stdout=None, stderr=None)
		queue_process.append(subproc)
		print "create queue process pid=", subproc.pid

	while shutdown == False :
		time.sleep(1)
		for process in queue_process:
			if process.poll() is not None:
				print process.pid, " is dead."
				queue_process.remove(process)
				child = subprocess.Popen(cmds, close_fds=True, stdin=None, stdout=None, stderr=None)
				print "create queue process pid=", child.pid
				queue_process.append(child)


if __name__ == '__main__':
	main()		
