#!/usr/bin/env python
# vim:set ts=4 sw=4:

import os, sys, commands, time, signal, ConfigParser

# value of variables pidfile and pyfred_server are replaced by setup.py
# during install phase
pidfile = '/var/run/pyfred.pid'
pyfred_server = '/usr/bin/fred-pyfred'

def usage():
	sys.stderr.write("Usage: pyfredctl [ start | stop | status ]\n")
	sys.stderr.write("\n")

def getpid(pidfile):
	"""
	Read pid from pidfile.
	"""
	try:
		fd = open(pidfile, "r")
	except Exception, e:
		return None

	pidline = fd.readline()
	fd.close()
	if pidline[-1] == '\n':
		return int(pidline[:-1])
	else:
		return int(pidline)

def isrunning(pid):
	"""
	Return true if process with pid is running, otherwise false.
	"""
	stat, output = commands.getstatusoutput("ps -p %d" % pid)
	if len(output.splitlines()) == 2:
		return True
	return False


def main(argv):
	"""
	The main.
	"""
	global pidfile
	global pyfred_server

	if len(argv) != 2:
		sys.stderr.write("Invalid parameter count\n")
		usage()
		sys.exit(2)
	command = argv[1]

	# assume default pid file location - this may not work always!
	pid = getpid(pidfile)

	if command == "start":
		if pid:
			if isrunning(pid):
				sys.stdout.write(pyfred_server+" is already running. Exiting.\n")
				sys.exit(1)
			sys.stdout.write("Found pidfile - perhaps unclean previous "
					"shutdown?\n")
			os.unlink(pidfile)

		pid = os.spawnl(os.P_WAIT, pyfred_server, pyfred_server)
		sys.stdout.write(pyfred_server+" was started\n")

	elif command == "stop":
		if not pid:
			sys.stdout.write(pyfred_server+" is not running. Exiting.\n")
			sys.exit(1)
		sys.stdout.write("Killing pid %d.\n" % pid)
		os.kill(pid, signal.SIGTERM)
		sys.stdout.write("Waiting 3 seconds for proces to terminate\n")
		time.sleep(3)
		if isrunning(pid):
			sys.stdout.write(pyfred_server+" doesn't want to exit\n")
			os.kill(pid, signal.SIGKILL)

	elif command == "status":
		if pid:
			sys.stdout.write(pyfred_server+" is running with pid %d.\n" % pid)
		else:
			sys.stdout.write(pyfred_server+" is not running.\n")

	else:
		sys.stderr.write("Invalid command specified\n")
		usage()
		sys.exit(2)

	sys.exit()


if __name__ == "__main__":
	main(sys.argv)
