#!/usr/bin/env python

import sys, os, signal

def startup(opt):
	if opt.pnfs:
		do_startup(opt, 'pnfs')
	if opt.pnws:
		do_startup(opt, 'pnws')

def do_startup(opt, name):
	global logdir, piddir, confdir
	base_port = globals()['%s_port' % name]
	processes = globals()['%s_processes' % name]
	executable = os.path.join(homedir, 'bin', name)
	config = os.path.join(confdir, '%s.conf' % name)
	for i in xrange(processes):
		port = base_port + i
		pidfile = os.path.join(piddir, '%s_%s.pid' % (name, port))
		logfile = os.path.join(logdir, '%s_%s.log' % (name, port))
		os.system('%s --port=%s --logfile=%s --pidfile=%s --config=/%s' % (
				executable, port, logfile, pidfile, config))

def shutdown(opt):
	if opt.pnfs:
		do_shutdown(opt, 'pnfs')
	if opt.pnws:
		do_shutdown(opt, 'pnws')

def do_shutdown(opt, name):
	global piddir
	base_port = globals()['%s_port' % name]
	processes = globals()['%s_processes' % name]
	for i in xrange(processes):
		port = base_port + i
		pidfile = os.path.join(piddir, '%s_%s.pid' % (name, port))
		if os.path.exists(pidfile):
			f = open(pidfile, 'r')
			pid = int(f.read())
			f.close()
			os.kill(pid, signal.SIGKILL)
			os.remove(pidfile)

def restart(opt):
	shutdown(opt)
	startup(opt)

def update(opt):
	os.system('svn update')
	restart(opt)

homedir = os.path.normpath(os.path.join(os.path.dirname(os.path.abspath(sys.argv[0])), os.pardir))
logdir = os.path.join(homedir, 'logs')
piddir = os.path.join(homedir, 'pid')
confdir = os.path.join(homedir, 'conf')

if not os.path.exists(logdir):
	os.mkdir(logdir)

if not os.path.exists(piddir):
	os.mkdir(piddir)

pnfs_port = 7001
pnfs_processes = 1

pnws_port = 8500
pnws_processes = 1

from optparse import OptionParser
parser = OptionParser()
parser.add_option("--nofs", dest="pnfs", action="store_false")
parser.add_option("--nows", dest="pnws", action="store_false")
parser.add_option("--startup", action="store_const", dest="action", const="startup")
parser.add_option("--shutdown", action="store_const", dest="action", const="shutdown")
parser.add_option("--restart", action="store_const", dest="action", const="restart")
parser.add_option("--update", action="store_const", dest="action", const="update")

parser.set_defaults(action="update", pnfs=True, pnws=True)

(options, args) = parser.parse_args()

os.chdir(homedir)
globals()[options.action](options)
