#!/usr/bin/env python

##############################################################################
#									     									 #		
# Jay Loden	jloden@gmail.com	http://jayloden.com/		     			 #
#									     									 #
# service.py: Duplicate the actions of the "service" command from RedHat for #
# Debian based distributions (TODO: work with other distro compatibility)    #
# 									     									 #
# June 11, 2005								     							 #
#									     									 #
##############################################################################

import getopt
import os, sys

version = ".01"
service_dir = "/etc/init.d/"
os.chdir(service_dir)

def getServices():
	'''search through the services in the service dir and return a list containing
	the file names that contain start|stop (services that are controllable).'''
	grepls = os.popen('grep -l "start|stop" *')
	svcfiles = grepls.read().splitlines()
	grepls.close()
	return svcfiles

def svc_start(service):
	'''Run the start option on the service given. Runtime code should verify that
	the service is part of the getServices() list before executing'''
	print "Starting service %s" % (service)
	os.system("./" + service + " start")
	print

def svc_stop(service):
	'''Run the stop option on the given service. Runtime code should check that
	this service is part of the list returned from getServices()'''
	print "Stopping service %s" % (service)
	os.system("./" + service + " stop")
	print

def svc_status(service):
	'''Print status of given service, if status is an existing option. Does
	not check if service is a valid service'''
	hndl = open(service)
	if hndl.read().find("|status") != -1:
		print "Status of %s:" % (service)
		os.system("./" + service + " status")
	
	else:
		print "ERROR: service \"%s\" does not recognize \"status\" option" % (service)
		sys.exit(2)

def svc_restart(service):
	'''For the service given, check the script for 'reload' or 'restart'. If
	'reload' is found, run 'service reload', etc. If neither is found, stop the
	service then start it again.'''
	hndl = open(service)
	if hndl.read().find("|reload") != -1:
		print "Restarting service %s" % (service)
		os.system("./" + service + " reload")
		print 

	elif hndl.read().find("|restart") != -1:
		print "Reloading service %s" % (service)
		os.system("./" + service + " restart")
		print

	else:
		svc_full_restart(service)

	hndl.close()

def svc_full_restart(service):
	'''Do a full restart of the given service (start then stop)'''
	print "Stopping and starting service %s" % (service)
	svc_stop(service)
	svc_start(service)
	print 

def svc_restart_all(services):
	'''Do a full restart of ALL services (start then stop)'''
	for svc in services:
		svc_full_restart(svc)

def svc_status_all(services):
	'''Give status of all services with a status option'''
	for svc in services:
	        hndl = open(svc)
        	if hndl.read().find("|status") != -1:
                	print "Status of %s:" % (svc)
                	os.system("./" + svc + " status")
	print

def listServices(services):
	'''given a list of services, display them all. TODO: have it detect the size of
	the terminal window and output more than one per line if possible, like 'ls'
	would'''
	print "Available Services:"
	for svc in services:
		#print "%s\t" % (svc),
		print svc

def usage():
	'''just print usage'''
	use = '''Usage: service -[Rfshvl] SERVICE ARGUMENTS
        -f|--full-restart:      Do a fullrestart of the service.
        -R|--full-restart-all:  Do a fullrestart of all services currently running.
        -s|--status-all:        Print a status of all services.
        -d|--debug:             Launch with debug.
        -h|--help:              This help.
        -v|--version:           Print version.
        -l|--list:              List all available services.

RedHat service clone (c) Jay Loden version %s''' % (version)

	print use

def ver():
	'''print the version of the program'''
	print "\nService (clone) Version: %s\n" % (version)

def main():
	svcs = getServices()

	try:
		options,args = getopt.getopt(sys.argv[1:], "Rf:shvl", ["list", "full-restart=", "full-restart-all", "status-all", "help", "version"])
	except getopt.GetoptError:
		# print help information and exit:
		usage()
		sys.exit(2)

	for opt,val in options:
		if opt in ("-R", "--full-restart-all"):
			svc_restart_all(svcs)
			sys.exit()
	
		if opt in ("-f", "--full-restart"):
			if val in svcs:
				svc_full_restart(val)
				sys.exit()
			else:
				print "\nERROR: service \"%s\" is not a valid service!\n" % (val)
				sys.exit(2)

		if opt in ("-s", "--status-all"):
			svc_status_all(svcs)
			sys.exit()

		if opt in ("-h", "--help"):
			usage()
			sys.exit()

		if opt in ("-l", "--list"):
			listServices(svcs)
			sys.exit()

		if opt in ("-v", "--version"):
			ver()
			sys.exit()
	
	if len(args) == 2:
		if args[0] in svcs:
			if args[1] == "start":
				svc_start(args[0])
		
			elif args[1] == "stop":
				svc_stop(args[0])

			elif args[1] == "status":
				svc_status(args[0])

			elif args[1] in ("restart", "reload"):
				svc_restart(args[0])

			else:
				os.system("./%s %s" % (args[0], args[1]))
	
		else: 
			print "\nERROR: unrecognized service \"%s\"" % (args[0])
			usage()
			sys.exit(2)

	else:
		print "\nERROR: wrong number of arguments given!"
		usage()
		sys.exit()
		
main()

