#!/usr/bin/env python
import re
import string
#import pdb
import xmllib
import os
import sys
#import posix
import pwd
import fcntl

#
# 
class Parser(xmllib.XMLParser):
	# 
	def __init__(self, file=None):
		xmllib.XMLParser.__init__(self)
		self.__data = []
		self.authors = []
		self.out = ""
		self.__pre_author = ""
		self.add_current_author = os.getuid()
		if file:
			self.load(file)

	def load(self,file): 
		while 1: 
			s=file.read(512)
			if not s: 
				break
			self.feed(s)
		self.close()

	def start_sipb(self,attrs): 
		self.__data.append('<sipb>')

	def end_sipb(self) : 
		self.out = string.join(self.__data,"")

	def unknown_starttag(self,tag,attrs):
		self.__data.append("<"+tag+">")

	def unknown_endtag(self,tag):
		line = self.__data.pop()
		line = self.__data.pop() +line
		self.__data.append(line + "</"+tag+">")
		if tag == 'sipb' :
			print self.__data

	def handle_data(self,data):
		self.__data.append(data)


	def start_author(self,attrs): 
		if self.__pre_author == '' : 
			self.__pre_author = 'a'
			self.__data.append('ADD_AUTHORS_HERE')

		if self.add_current_author == int(attrs['id']): 
			self.add_current_author = -1
		line = '<author '

		for att in attrs.keys(): 
			line += att + '="' + attrs[att] +'" '
		line += '>'
		self.authors.append( line)

		
	def end_author(self): 
		line = self.__data.pop()
		# complete the self.authors list
		self.authors.append(self.authors.pop()+line +'</author>')

try: 
	os.chdir("/afs/sipb/project/www/knowledge-base/sipbml")
	p = Parser()
	p.load(open(sys.argv[1]))


#	Add the entry for the new author if need be..

except EOFError: 
	pass

# Add an author entry if there isn't one for the 
# current guy. 

if p.add_current_author != -1: 
	p.authors.append('<author id="' + repr(p.add_current_author) +'" order="' + repr(len(p.authors)+1) +'">' +pwd.getpwuid(os.getuid())[4] +'</author>'  ) 

lout = re.sub('ADD_AUTHORS_HERE', string.join(p.authors,''),p.out)
print lout

# RCS check it out. 
# reparse the sucker.
#f = os.popen('co -l ' + sys.argv[1])
#print f.read()
#f.close()
# f = open(sys.argv[1],'w').write(lout)

# call $VISUAL
status = 'edit'

# invoke $EDITOR on it. 
while status[0] == 'e' : 
	os.system(os.environ["VISUAL"] + " " + id)
	status = raw_input('What now? edit, save, quit >')


# reparse.
# parse and process the file. Done!
if status[0] == 's' : 
	print "Generating an HTML file... "
# That last word in the command line is what 
# tells the parser to give us the title for RCS.
# kbedit will ask for the author tags.
	p = os.popen('python python/sipb1.py ' + id + ' ../html/'+id+' title')
	title=p.read()
	p.close()
