#!/usr/bin/python

import sys, getopt, os, os.path, fnmatch, string, StringIO

#---------- globals ----------

FALSE     = 0
TRUE      = not FALSE

ops       = ['tr', 'qtNoTr', 'shpix']
operation = ''
opPath    = ''
pattern   = ''


# --------- support functions ----------

def getOptions ():
	global pattern
	arglist = sys.argv [1:]
	shortOptions = "p:o:"
	longOptions  = "path= op="

	try:
		optlist, args = getopt.getopt (arglist, shortOptions, longOptions)
	except getopt.GetoptError:
		optlist = []
		args    = []

	if (optlist == []) or (len (args) != 1):
		print '\nUsage: postproc -p<path> -o<operation> <filespec>\n'
		return FALSE

	pattern = args [0]
	return checkOptions (optlist)

def checkOptions (optlist):
	havePath = FALSE
	haveOp   = FALSE

	for pair in optlist:
		if (pair [0] == '--path') or (pair [0] == '-p'):
			if not checkPath (pair [1]):
				print '\nPath ' + pair [1] + ' does not exist\n'
			else:
				havePath = TRUE

		elif (pair [0] == '--op') or (pair [0] == '-o'):
			if not checkOp (pair [1]):
				print '\nOperation ' + pair [1] + ' does not exist\n'
			else:
				haveOp = TRUE

	return havePath and haveOp

def checkPath (path):
	global opPath
	if not os.path.exists (path):
		return FALSE

	opPath = path
	if not (opPath [-1] == '/'):
		opPath = opPath + '/'

	return TRUE


def checkOp (op):
	global operation
	if not op in ops:
		return FALSE

	operation = op
	return TRUE

def getFilelist ():
	filelist = []
	tmpfilelist = os.listdir (opPath)
	for fn in tmpfilelist:
		if fnmatch.fnmatchcase (fn, pattern):
			filelist.append (fn)

	return filelist

# --------- operations ----------

# removes sipDo_<classname>_tr and table reference ('sipName_qt_tr')
# because KDE2 is compiled with QT_NO_TRANSLATION defined (which also
# makes QObject::tr methods invisible to any KDE2 QObject descendants)

def trFix (filelist):
	for fn in filelist:
		m       = open (opPath + fn, 'r')
		tmpname = os.path.splitext (fn) [0] + '.tmp'
		tmp     = StringIO.StringIO ()

		buff    = m.readlines ()
		m.close ()

		i       = 0
		nLines  = len (buff)

		# skip leading comments
		while (i < nLines) and (buff [i][0:1] == '//'):
			tmp.write (buff [i])
			i = i + 1

		# find classname
   		while (i < nLines) and (not string.find (buff [i], 'PyObject *sipClass_') == 0):
			tmp.write (buff [i])
			i = i + 1

   		if i >= nLines: 	# no classname - don't bother
			tmp.close ()
			continue

		classname = buff [i][19:-2]

		trStr = 'static PyObject *sipDo_' + classname + '_tr(PyObject *sipThisObj,PyObject *sipArgs)\n'

		while (i < nLines) and (buff [i] != trStr):
			tmp.write (buff [i])
			i = i + 1

   		if i >= nLines:		# no sipDo_*_tr - done
			tmp.close ()
			continue

		# skip over this method without writing it out
		while (i < nLines) and (buff [i][0] != '}'):
			i = i + 1

   		i = i + 1 	# skip the '}' too


		while (i < nLines):
			# skip sipName_qt_tr table entry/write out everything else
			if string.find (buff [i], '{sipName_qt_tr') < 0:
				tmp.write (buff [i])
			i = i + 1

		tmpfile = open (opPath + tmpname, 'w')
		tmpfile.write (tmp.getvalue ())
		tmpfile.close ()
		tmp.close ()
		os.unlink (opPath + fn)
		os.rename (opPath + tmpname, opPath + fn)

	return TRUE

def qtNoTr (filelist):
	for fn in filelist:
		print fn
		m       = open (opPath + fn, 'r')
		tmpname = os.path.splitext (fn) [0] + '.tmp'
		tmp     = StringIO.StringIO ()

		buff    = m.readlines ()
		m.close ()

		i       = 0
		nLines  = len (buff)

		while (i < nLines) and (string.find (buff [i], 'Q_OBJECT') < 0):
			tmp.write (buff [i])
			i = i + 1

		tmp.write ("#define QT_NO_TRANSLATION\n")

		while (i < nLines):
			tmp.write (buff [i])
			i = i + 1

		tmpfile = open (opPath + tmpname, 'w')
		tmpfile.write (tmp.getvalue ())
		tmpfile.close ()
		tmp.close ()
		os.unlink (opPath + fn)
		os.rename (opPath + tmpname, opPath + fn)

	return TRUE

# changes QPaintDevice to KPixmap for two method calls
# gcc reports QPaintDevice as "ambiguous"
	
def shpix ():
	fn      = opPath + 'sipkdeuiKSharedPixmap.cpp'
	m       = open (fn, 'r')
	tmpname = os.path.splitext (fn) [0] + '.tmp'

	buff    = m.read ()
	m.close ()
	buff = string.replace (buff, "QPaintDevice::resolution", "KPixmap::resolution")
	buff = string.replace (buff, "QPaintDevice::setResolution", "KPixmap::setResolution")

	tmpfile = open (tmpname, 'w')
	tmpfile.write (buff)
	tmpfile.close ()
	os.unlink (fn)
	os.rename (tmpname, fn)

	return TRUE





# --------- main ----------

if not getOptions ():
	sys.exit (-1)

filelist = getFilelist ()
if filelist == []:
	sys.exit (0)

if operation == "tr":
	if not trFix (filelist):
		print 'operation error -- tr'
		sys.exit (-1)

elif operation == 'qtNoTr':
	if not qtNoTr (filelist):
		print 'operation error -- qtNoTr'
		sys.exit (-1)

elif operation == 'shpix':
	if not shpix ():
		print 'operation error -- shpix'
		sys.exit (-1)

sys.exit (0)
