#!/usr/bin/python

import os
import time
import sys


#pid_file = os.path.join(os.path.abspath(__file__), "fcgi.pid")
pid_file = "/var/run/fcgi.pid"
nginx_command = "python manage.py runfcgi host=127.0.0.1 port=8080 maxchildren=5 maxspare=5 minspare=2 method=prefork pidfile={0}".format(pid_file)
sleep_time = 4.0

def kill():
    try:
        with open(pid_file, 'r') as f:
            old_pid = f.read()
            os.system("kill -HUP {0}".format(old_pid))         
	    time.sleep(sleep_time)
            os.remove(pid_file)
    except IOError:
        print "Django FastCGI process not currently running" 
        sys.exit()



def start():
    print pid_file
    os.system(nginx_command)


if __name__ == '__main__':
    args = sys.argv
    try:
        if args[1] == "start":
            start()
        elif args[1] == "restart":
            kill()
            start()
        elif args[1] == "stop":
            kill()
        else: 
            raise IndexError
    except IndexError:
        print "No command detected among (start|restart|stop)"
        sys.exit()

 
