#! %%PYTHON_CMD%%

################################################################################
# Author:        Jean-Baptiste Quenot <jb.quenot@caraldi.com>
# Purpose:       Control cocoon process
# Date Created:  2004-05-04 11:14:05
# Revision:      $FreeBSD: ports/www/cocoon/files/cocoonctl,v 1.1 2004/07/01 22:30:19 glewis Exp $
################################################################################

import sys, os, signal, time

LOGFILE = "%%LOGFILE%%"
PREFIX = "%%PREFIX%%"
APP_NAME = "%%APP_NAME%%"
PID_FILE = "%%PID_FILE%%"

if __name__ == '__main__':
    if sys.argv[1] == "start":
        # Append cocoon output to a log file
        l = open(LOGFILE, 'a')
        os.dup2(l.fileno(), sys.stdout.fileno())
        os.dup2(l.fileno(), sys.stderr.fileno())

        # Start cocoon in the background
        command = PREFIX + "/sbin/" + APP_NAME + ".sh"
        pid = os.spawnl(os.P_NOWAIT, command, command, "servlet")

        # Wait a little
        time.sleep(0.4)

        # Send a dummy signal to the process.  If it died, an exception is
        # thrown
        os.kill(pid, signal.SIGCONT)

        # It's alive, so write down the process id
        f = open(PID_FILE, 'w')
        print >> f, pid
        f.close()
    elif sys.argv[1] == "stop":
        # Read the process id
        f = open(PID_FILE, 'r')
        pid = int(f.readline())
        f.close()

        # Terminate cocoon
        os.kill(pid, signal.SIGTERM)
    else:
        print "Usage: %s start|stop" % sys.argv[0]
