import apachegui
from apachegui import *
import apache
import Conf

# Variable initialization
VERSION = "0.2"
COPYRIGHT = "Copyright (C) 1997 Alejandro Escalante Medina and others\nRedistributable \
under the terms of the GNU General Public License"

# This is the configuration file for the configurator :)
apachecfgpath = "/var/lib/apachecfg/"
ourcfg = Conf.ConfShellVar(apachecfgpath + "apachecfg.cfg")
apachegui.showballoons = ourcfg['ShowBalloons']
restarthttpd = ourcfg['RestartHttpd']
svshowballoons = StringVar()
svrestarthttpd = StringVar()

httpdcfg = apache.httpd()
httpdvars = {}
for i in apache.getvalidkeys("httpd").keys():
	httpdvars[i] = StringVar()
	httpdvars[i].set(httpdcfg[i])

accesscfg = apache.access()
accessvars = {}
for i in apache.getvalidkeys("access").keys():
	accessvars[i] = StringVar()
	accessvars[i].set(accesscfg[i])

srmcfg = apache.srm()
srmvars = {}
for i in apache.getvalidkeys("srm").keys():
	srmvars[i] = StringVar()
	srmvars[i].set(srmcfg[i])

# Print Some info
print "Red Hat Linux apachecfg", VERSION
print COPYRIGHT

# httpd.conf stuff

class HttpdMain(SubFrame):
	def __init__(self, Master):
		SubFrame.__init__(self, Master)
		#Draw the interface
		self.addBoundControl("ServerType", httpdvars["ServerType"], 12, "m[standalone|inetd]", apache.gethelpstring("ServerType"))
		self.addBoundControl("ServerRoot", httpdvars["ServerRoot"], 12, "f", apache.gethelpstring("ServerRoot"))
		self.addBoundControl("User", httpdvars["User"], 12, "s", apache.gethelpstring("User"))
		self.addBoundControl("Group", httpdvars["Group"], 12, "s", apache.gethelpstring("Group"))
		self.addBoundControl("Port", httpdvars["Port"], 12, "s", apache.gethelpstring("Port"))
		self.addBoundControl("ServerName", httpdvars["ServerName"], 12, "s", apache.gethelpstring("ServerName"))
		self.addBoundControl("ServerAdmin", httpdvars["ServerAdmin"], 12, "s", apache.gethelpstring("ServerAdmin"))

class HttpdLogs(SubFrame):
	def __init__(self, Master):
		SubFrame.__init__(self, Master)
		#Draw the interface
		self.addBoundControl("ErrorLog", httpdvars["ErrorLog"], 12, "s", apache.gethelpstring("ErrorLog"))
		self.addBoundControl("TransferLog", httpdvars["TransferLog"], 12, "s", apache.gethelpstring("TransferLog"))
		self.addBoundControl("AgentLog", httpdvars["AgentLog"], 12, "s", apache.gethelpstring("AgentLog"))
		self.addBoundControl("RefererLog", httpdvars["RefererLog"], 12, "s", apache.gethelpstring("RefererLog"))

class HttpdCapacity(SubFrame):
	def __init__(self, Master):
		SubFrame.__init__(self, Master)
		#Draw the interface
		self.addBoundControl("KeepAlive", httpdvars["KeepAlive"], 20, "n")
		self.addBoundControl("KeepAliveTimeOut", httpdvars["KeepAliveTimeout"], 20, "n")
		self.addBoundControl("MinSpareServers", httpdvars["MinSpareServers"], 20, "n")
		self.addBoundControl("MaxSpareServers", httpdvars["MaxSpareServers"], 20, "n")
		self.addBoundControl("StartServers", httpdvars["StartServers"], 20, "n")		
		self.addBoundControl("MaxClients", httpdvars["MaxClients"], 20, "n")
		self.addBoundControl("MaxRequestsPerChild", httpdvars["MaxRequestsPerChild"], 20, "n")

class HttpdOther(SubFrame):
	def __init__(self, Master):
		SubFrame.__init__(self, Master)
		#Draw the interface
		self.addBoundControl("PidFile", httpdvars["PidFile"], 18, "f")
		self.addBoundControl("SocreBoardFile", httpdvars["ScoreBoardFile"], 18, "f")
		self.addBoundControl("HostnameLookups", httpdvars["HostnameLookups"], 18, "b")

class HttpdVirtualHosts(SubFrame):
	def __init__(self, Master):
		SubFrame.__init__(self, Master)
		#Draw the interface
		self.vhostl = RHListbox(self)
		self.vhostl.pack({'side':'top', 'fill':'both', 'expand':'1'})
		for v in httpdcfg.virtualhosts():
			self.vhostl.insert(0, v)  
		f2 = RHFrame(self)
		b = Button(f2, {'text':'Add','command':self.addVhost})
		b.pack({'side':'left','fill':'x'})
		b = Button(f2, {'text':'Edit','command':self.editVhost})
		b.pack({'side':'left','fill':'x'})
		b = Button(f2, {'text':'Delete','command':self.delVhost})
		b.pack({'side':'left','fill':'x'})
		f2.pack({'side':'top'})   
	def addVhost(self):
		v = StringVar()
		d = MyDialog("Add virtual host")
		d.addBoundControl("Virtual host name", v, 18, "s")
		d.show()
		if(v.get() != "" and v.get() != None):
			thehost = httpdcfg.VirtualHost(v.get())
			self.vhostl.insert(0, v.get())    
	def editVhost(self):
		if(self.vhostl.curselection() == ()):
			return
		d = MyDialog("Edit virtual host")
		thehost = httpdcfg.VirtualHost(self.vhostl.get(self.vhostl.curselection()))
		vvars = {}
		for i in thehost.validkeys.keys():
			vvars[i] = StringVar()
			if thehost[i]:
				vvars[i].set(thehost[i])
			else:
				vvars[i].set("")
			d.addBoundControl(i, vvars[i], 18, apache.getvalidkeys("VirtualHost")[i])
		d.show()
		for i in vvars.keys():
			v = vvars[i].get()
			if v:
				thehost[i] = v   
	def delVhost(self):
		if(self.vhostl.curselection() == ()):
			return
		httpdcfg.virtualhost_del(self.vhostl.get(self.vhostl.curselection()))
		self.vhostl.delete(self.vhostl.curselection())

# access.conf stuff

class AccessDirectories(SubFrame):
	def __init__(self, Master):
		SubFrame.__init__(self, Master)
		#Draw the interface
		self.dirl = RHListbox(self)
		self.dirl.pack({'side':'top','fill':'both','expand':'1'})
		for v in accesscfg.directories():
			self.dirl.insert(0, v)  
		f2 = RHFrame(self)
		b = Button(f2, {'text':'Add','command':self.addDir})
		b.pack({'side':'left','fill':'x'})
		b = Button(f2, {'text':'Edit','command':self.editDir})
		b.pack({'side':'left','fill':'x'})
		b = Button(f2, {'text':'Delete','command':self.delDir})
		b.pack({'side':'left','fill':'x'})
		f2.pack({'side':'top'})
	def addDir(self):
		v = StringVar()
		d = MyDialog("Add directory")
		d.addBoundControl("Directory name", v, 18, "s")
		d.show()
		if(v.get() != "" and v.get() != None):
			thedir = accesscfg.Directory(v.get())
			self.dirl.insert(0, v.get())    
	def editDir(self):
		if(self.dirl.curselection() == ()):
			return
		d = MyDialog("Edit directory")
		thedir = accesscfg.Directory(self.dirl.get(self.dirl.curselection()))
		vvars = {}
		for i in thedir.validkeys.keys():
			vvars[i] = StringVar()
			if thedir[i]:
				vvars[i].set(thedir[i])
			else:
				vvars[i].set("")
			d.addBoundControl(i, vvars[i], 18, apache.getvalidkeys("Directory")[i])
		d.show()
		for i in vvars.keys():
			v = vvars[i].get()
			if v:
				thedir[i] = v   
	def delDir(self):
		if(self.dirl.curselection() == ()):
			return
		accesscfg.directory_del(self.dirl.get(self.dirl.curselection()))
		self.dirl.delete(self.dirl.curselection())

class AccessLocations(SubFrame):
	def __init__(self, Master):
		SubFrame.__init__(self, Master)
		#Draw the interface
		self.locl = RHListbox(self)
		self.locl.pack({'side':'top','fill':'both','expand':'1'})
		for v in accesscfg.locations():
			self.locl.insert(0, v)  
		f2 = RHFrame(self)
		b = Button(f2, {'text':'Add','command':self.addLoc})
		b.pack({'side':'left','fill':'x'})
		b = Button(f2, {'text':'Edit','command':self.editLoc})
		b.pack({'side':'left','fill':'x'})
		b = Button(f2, {'text':'Delete','command':self.delLoc})
		b.pack({'side':'left','fill':'x'})
		f2.pack({'side':'top'})
	def addLoc(self):
		v = StringVar()
		d = MyDialog("Add location")
		d.addBoundControl("Location name", v, 18, "s")
		d.show()
		if(v.get() != "" and v.get() != None):
			theloc = accesscfg.Location(v.get())
			self.locl.insert(0, v.get())    
	def editLoc(self):
		if(self.locl.curselection() == ()):
			return
		d = MyDialog("Edit location")
		theloc = accesscfg.Location(self.locl.get(self.locl.curselection()))
		vvars = {}
		for i in theloc.validkeys.keys():
			vvars[i] = StringVar()
			if theloc[i]:
				vvars[i].set(theloc[i])
			else:
				vvars[i].set("")
			d.addBoundControl(i, vvars[i], 18, apache.getvalidkeys("Location")[i])
		d.show()
		for i in vvars.keys():
			v = vvars[i].get()
			if v:
				theloc[i] = v   
	def delLoc(self):
		if(self.locl.curselection() == ()):
			return
		accesscfg.location_del(self.locl.get(self.locl.curselection()))
		self.locl.delete(self.locl.curselection())

# srm.conf stuff

class SrmMain(SubFrame):
	def __init__(self, Master):
		SubFrame.__init__(self, Master)
		#Draw the interface
		h = apache.getvalidkeys("srm")
		for i in h.keys():
			self.addBoundControl(i, srmvars[i], 18, h[i])
class SrmScriptAlias(SubFrame):
	def __init__(self, Master):
		SubFrame.__init__(self, Master)
		#Draw the interface
		self.sal = RHListbox(self)
		self.sal.pack({'side':'top','fill':'both','expand':'1'})
		i = 0
		for v in srmcfg["ScriptAlias"]:
			self.sal.insert(i, v)
			i = i + 1
		f2 = RHFrame(self)
		b = Button(f2, {'text':'Add','command':self.addSA})
		b.pack({'side':'left','fill':'x'})
		b = Button(f2, {'text':'Delete','command':self.delSA})
		b.pack({'side':'left','fill':'x'})
		f2.pack({'side':'top'})
	def addSA(self):
		fake = StringVar()
		real = StringVar()
		d = MyDialog("Add ScriptAlias")
		d.addBoundControl("Fake name", fake, 18, "s")
		d.addBoundControl("Real name", real, 18, "s")
		d.show()
		if(fake.get() != "" and fake.get() != None):
			if(real.get() != "" and real.get() != None):
				srmcfg["ScriptAlias"].append(fake.get() + " " + real.get())
				self.sal.insert(len(srmcfg["ScriptAlias"]), fake.get() + " " + real.get())    
			else:
				Dialog('Error', "A real path is needed", 'error', 0, ['Ok']).num
		else:
			Dialog('Error', "A fake path is needed", 'error', 0, ['Ok']).num
	def delSA(self):
		if(self.sal.curselection() == ()):
			return
		del srmcfg["ScriptAlias"][string.atoi(self.sal.curselection()[0])]
		self.sal.delete(self.sal.curselection())
class SrmAlias(SubFrame):
	def __init__(self, Master):
		SubFrame.__init__(self, Master)
		#Draw the interface
		self.sal = RHListbox(self)
		self.sal.pack({'side':'top','fill':'both','expand':'1'})
		i = 0
		for v in srmcfg["Alias"]:
			self.sal.insert(i, v)
			i = i + 1
		f2 = RHFrame(self)
		b = Button(f2, {'text':'Add','command':self.addAlias})
		b.pack({'side':'left','fill':'x'})
		b = Button(f2, {'text':'Delete','command':self.delAlias})
		b.pack({'side':'left','fill':'x'})
		f2.pack({'side':'top'})
	def addAlias(self):
		fake = StringVar()
		real = StringVar()
		d = MyDialog("Add Alias")
		d.addBoundControl("Fake name", fake, 18, "s")
		d.addBoundControl("Real name", real, 18, "s")
		d.show()
		if(fake.get() != "" and fake.get() != None):
			if(real.get() != "" and real.get() != None):
				srmcfg["Alias"].append(fake.get() + " " + real.get())
				self.sal.insert(len(srmcfg["Alias"]), fake.get() + " " + real.get())
			else:
				Dialog('Error', "A real path is needed", 'error', 0, ['Ok']).num
		else:
			Dialog('Error', "A fake path is needed", 'error', 0, ['Ok']).num
	def delAlias(self):
		if(self.sal.curselection() == ()):
			return
		del srmcfg["Alias"][string.atoi(self.sal.curselection()[0])]
		self.sal.delete(self.sal.curselection())
class SrmAddHandler(SubFrame):
	def __init__(self, Master):
		SubFrame.__init__(self, Master)
		#Draw the interface
		self.sal = RHListbox(self)
		self.sal.pack({'side':'top','fill':'both','expand':'1'})
		i = 0
		for v in srmcfg["AddHandler"]:
			self.sal.insert(i, v)
			i = i + 1
		f2 = RHFrame(self)
		b = Button(f2, {'text':'Add','command':self.addAddHandler})
		b.pack({'side':'left','fill':'x'})
		b = Button(f2, {'text':'Delete','command':self.delAddHandler})
		b.pack({'side':'left','fill':'x'})
		f2.pack({'side':'top'})
	def addAddHandler(self):
		handler = StringVar()
		ext = StringVar()
		d = MyDialog("Add AddHandler")
		d.addBoundControl("Handler", handler, 18, "s")
		d.addBoundControl("File extension", ext, 18, "s")
		d.show()
		if(handler.get() != "" and handler.get() != None):
			if(ext.get() != "" and ext.get() != None):
				srmcfg["AddHandler"].append(handler.get() + " " + ext.get())
				self.sal.insert(len(srmcfg["AddHandler"]), handler.get() + " " + ext.get())
			else:
				Dialog('Error', "An extension is needed", 'error', 0, ['Ok']).num
		else:
			Dialog('Error', "A handler is needed", 'error', 0, ['Ok']).num
	def delAddHandler(self):
		if(self.sal.curselection() == ()):
			return
		del srmcfg["AddHandler"][string.atoi(self.sal.curselection()[0])]
		self.sal.delete(self.sal.curselection())

#
# Other things: Our own configuration, the about box...
#


class Other(SubFrame):
	def __init__(self, Master):
		SubFrame.__init__(self, Master)

class OtherHelp(SubFrame):
	def __init__(self, Master):
		SubFrame.__init__(self, Master)
		self.addBoundControl("Balloon help", svshowballoons, 18, "b")		

class OtherAbout(SubFrame):
	def __init__(self, Master):
		SubFrame.__init__(self, Master)
		l = Label(self)
		l['anchor'] = 'nw'
		l['justify'] = 'left'
		l['font'] = "-Adobe-Helvetica-Medium-R-Normal--*-120-*-*-*-*-*-*"
		l['text'] = "This program was written by:\n\nAlejandro Escalante, amedina@msg.com.mx\n\nThanks to:\n\nMiguel de Icaza, miguel@nuclecu.unam.mx\nElliot Lee, sopwith@redhat.com\nComision Federal de Electricidad, http://www.cfe.gob.mx\nMatias Software Group, http://www.msg.com"
		l.pack({'fill':'both','expand':'1'})

def write():
	try:
		# httpd
		for i in httpdvars.keys():
			v = httpdvars[i].get()
			if v:
				httpdcfg[i] = v
		httpdcfg.write()
		# access
		for i in accessvars.keys():
			v = accessvars[i].get()
			if v:
				accesscfg[i] = v
		accesscfg.write()
		# srm
		for i in srmvars.keys():
			v = srmvars[i].get()
			if v:
				srmcfg[i] = v
		srmcfg.write()
		# Our configuration
		ourcfg["BalloonHelp"] = svshowballoons.get()
		ourcfg["RestartHttpd"] = svrestarthttpd.get()
		ourcfg.write()
	except TypeError, msg:
		Dialog('Error', msg, 'error', 0, ['Ok']).num   

def quit():
	root.quit()

top = Toplevel()
top.minsize(500, 355)
top.maxsize(500, 355)
top.geometry('500x355')   
top.title("Apache configuratior 0.2")

root = TabFrame(top)
httpd = TabFrame(root.Frame, 'v')
httpd.addTab('Main', HttpdMain(httpd.Frame), "Configuration of the main options")
httpd.addTab('Logs', HttpdLogs(httpd.Frame), "Paths and names of log files")
httpd.addTab('Capacity', HttpdCapacity(httpd.Frame), "Parameters related to capacity and performance")
httpd.addTab('Other', HttpdOther(httpd.Frame), "Configuration of other options" )
httpd.addTab('VirtualHosts', HttpdVirtualHosts(httpd.Frame), "Virtual hosts management")

access = TabFrame(root.Frame, 'v')
access.addTab('Directories', AccessDirectories(access.Frame), "Directory access configuration")
access.addTab('Locations', AccessLocations(access.Frame), "Location access configuration")

srm = TabFrame(root.Frame, 'v')
srm.addTab('Main', SrmMain(srm.Frame), "Configuration of the main options")
srm.addTab('Alias', SrmAlias(srm.Frame), "Configuration of Alias")
srm.addTab('ScriptAlias', SrmScriptAlias(srm.Frame), "Configuration of ScriptAlias")
srm.addTab('AddHandler', SrmAddHandler(srm.Frame), "Configuration of handlers")

other = TabFrame(root.Frame, 'v')
other.addTab('Help', OtherHelp(other.Frame), "Help options")
other.addTab('About', OtherAbout(other.Frame), "About this program")

root.addTab('httpd.conf', httpd, "httpd.conf")
root.addTab('access.conf', access, "access.conf")
root.addTab('srm.conf', srm, 'srm.conf')
root.addTab('Other', other, 'Some other things')

f = RHFrame(top)
f.pack({'side':'bottom','fill':'x'})
SM = ButtonBar(f)
SM.setOrientation('horizontal')
SM.addButton('Save', write)
SM.addButton('Quit', quit)
SM.pack({'side':'right'})

# magic to keep a root window from appearing
L = Label()
L.tk.call('wm', 'withdraw', '.')
del L

root.show()
root.wait_window(root)
