#!/usr/local/bin/python

## BUG TO FIX :
##
## SIGHUP: error in signe on open(SIGNATURE, "w") ...

import os
import sys
import time
import string
import signal
import whrandom

# The globals variables

# signature file : ~/.signature
SIGNATURE = "%s/.signature" % os.environ["HOME"]

# content of the signature file on first load
SIG_HEADER = ""

# fortune file
FORTUNE_FILE = ""

# list of fortune in wich to choose
FORTUNE_LIST = []

def load():
	"""load FORTUNE_FILE and return a FORTUNE_LIST"""
	global FORTUNE_LIST
	
	file = open(FORTUNE_FILE, "r")
	buffer = file.read()
	file.close()

	# Now we get all the file into the buffer, but we have to separate the
	# different signatures from it.
	# Separation cars is "%" alone in its line

	FORTUNE_LIST = string.split(buffer, "\n%\n")[:-1]
	print "loaded %d signatures" % len(FORTUNE_LIST)

def signe():
	"""whenever filename is read, this will output a random choosen
	signature"""

	global SIG_HEADER
	
	# first load the file, which containe the static signature text
	file = open(SIGNATURE, "r")
	SIG_HEADER = file.read()
	file.close()

	# Now delete the file and open a pipe to write in random signatures
	os.unlink(SIGNATURE)
	sigfile = os.mkfifo(SIGNATURE)

	# The following has to be done forever ... or until death
	while 1:
		s_fd = open(SIGNATURE, "w")
		# On read, we produce that
		s_fd.write(SIG_HEADER)
		
		index = whrandom.randint(0, len(FORTUNE_LIST)-1)
		fortune = FORTUNE_LIST[index]
		
		s_fd.write("\n%s" % fortune)
		s_fd.close()

		# we sould wait a little
		time.sleep(1)

	# what if we arrive here ? grumpf
	print "We've got a problem, Houston"

# Now we have to be able to deal with signals, and first TERM
def terminate(sig, frame):
	"""when we receive the TERM signal, we have to clean the mess done"""
	# So first delete the fifo, and create the given file

	os.unlink(SIGNATURE)
	file = open(SIGNATURE, "w")
	file.write(SIG_HEADER)
	file.close()

	print "Random Signature Chooser Killed"

	sys.exit(0)

# Whenever we receive a HUP signal, we should re-read the fortunes file

if __name__ == "__main__":
	# command line call

	global FORTUNE_FILE

	if len(sys.argv) != 2:
		# usage error
		print "usage: signature.py <fortunes file>"
		sys.exit(1)
		
	# prevent from TERM signal
	signal.signal(signal.SIGTERM, terminate)

	# react on HUP signal to relaod the fortune file
	signal.signal(signal.SIGHUP, load)	

	# Now call the funcs to do the job
	FORTUNE_FILE = sys.argv[1]
	load()
	signe()
