#! /usr/bin/python

import os, re, string, sys, getopt

def version():
	print "Generic Colouriser 0.2"
	sys.exit()

def help():
	print "Generic Colouriser 0.2"
	print
	print "-e --stderr    redirect stderr. If this option is selected, "
	print "               do not automatically redirect stdout"
	print "-s --stdout    redirect stdout, even if -e is selected"
	print "-c=name --config=name    use name as configuration file for grcat"
	print
	sys.exit()


try:
	optlist, args = getopt.getopt(sys.argv[1:], "sec:", ["stdout", "stderr", "config="] )
except:
	help()

stdoutf = 0
stderrf = 0

# configure file for grcat
cfile = ""

for i in optlist:
	if i[0] in ["--stderr", "-e"]:
		stderrf = 1
	elif i[0] in ["--stdout", "-s"]:
		stdoutf = 1
	elif i[0] in ["--config", "-c"]:
		cfile = i[1]

stdoutff = 1
stderrff = 0
if stderrf == 1:
	stdoutff = 0
	stderrff = 1
if stdoutf == 1:
	stdoutff = 1

# this is so ugly... maybe needs to be rewriten using popen3
if stdoutff == 0 and stderrff == 1:
	cstr = " 2>&1 | grcat "
elif stdoutff == 1 and stderrff == 0:
	cstr = " | grcat "
elif stdoutff == 1 and stderrff == 1:
	cstr = " | grcat 2>&1 "


if cfile == "":
	conffilename = [os.environ['HOME']+"/.grc/grc.conf", "/etc/grc.conf"]
	for i in conffilename:
		if os.path.isfile(i):
			conffile = i
			break
	regexplist = []

	f = open(conffile, "r")
	while 1:
		l = f.readline()
		if l == "":
			break
		if l[0] == "#" or l[0] == '\012':
			continue
		regexp = l[:-1]
		if re.search(regexp, string.join(args)):
			cfile = f.readline()[:-1]
			break

if cfile != "":
	print string.join(args) + cstr + cfile
	os.system(string.join(args) + cstr + cfile)
else:
	print string.join(args)
	os.system(string.join(args))
 