#!/usr/bin/python
# Written by Eli Carter for Fedora Core 4

import os
import sys
import time

webbasedir = "/var/www"
templatedir = "/usr/share/trac/templates"
def install_software():
	os.system( "yum -y install mod_python subversion httpd trac" )
def get_project_config():
	print "Project Name:",
	name = raw_input()
	print "Repository: (blank for new)",
	repo = raw_input()
	while 0: # FIXME: we don't use the password info yet.
		print "Admin Password",
		passwd = raw_input()
		print "Admin Password (again)",
		passwd2 = raw_input()
		if passwd and passwd == passwd2:
			break
	config = {'name':name, 'repo':repo, 'date':time.asctime() }
	#config['passwd'] = passwd # FIXME: we don't use the password info yet.
	config['basename'] = config['name'].lower().replace(' ','')
	config['tracdir'] = os.path.join( webbasedir, 'trac', config['basename'] )
	return config
def setup_new_repository( pathname ):
	os.system( "mkdir -p `dirname %s`" % pathname )
	os.system( "svnadmin create \"%s\"" % pathname )
	os.system( "chown -R apache:apache %s" % pathname ) # FIXME: is this needed?
def configure_subversion( config ):
	# TODO: need to make subversion use the right usernames...
	pass
def configure_trac( config ):
	# Write out configuration files
	# run trac-admin
	os.system( "mkdir `dirname %(tracdir)s`" % config )
	os.system( "trac-admin %(tracdir)s initenv \"%(name)s\" sqlite:db/trac.db %(repo)s /usr/share/trac/templates" % config )
	# TODO: What changes are needed for trac.ini?
	#inifile = os.path.join( config['tracdir'], "conf/trac.ini" )
	#configfile = open( inifile, "w" )
	os.system( "chown -R apache:apache %(tracdir)s" % config )
def configure_apache( config ):
	# Write out configuration files
	configfilename = "/etc/httpd/conf.d/trac.conf"
	if os.path.isfile( configfilename ): # quick backup
		os.system( "cp %s{,.orig}" % configfilename )
	configfile = open( configfilename, "w" )
	template = ''.join([
		"# %(date)s\n",
		"<Location /%(basename)s>\n",
		"    SetEnv TRAC_ENV %(tracdir)s\n",
		#"<IfModule mod_python.c>\n",
		"    SetHandler mod_python\n",
		"    PythonHandler trac.web.modpython_frontend\n",
		"    PythonOption TracEnv %(tracdir)s\n",
		#"</IfModule>\n",
		"</Location>\n",
		#"<Location \"/%(basename)s/login\">\n",
		#"  AuthType Basic\n",
		#"  AuthName \"%(basename)s\"\n",
		#"  AuthUserFile %(tracdir)s/.htaccess\n",
		#"  Require valid-user\n",
		#"</Location>\n",
		])
	configfile.write( template % config )
	os.system( "service httpd restart" )

def do_setup():
	install_software() # Comment this out after the first run to speed things up
	config = get_project_config()
	if not config['repo']:
		config['repo'] = os.path.join( webbasedir, 'svn', config['basename'] )
	if not os.path.isdir( config['repo'] ):
		print "Creating new subversion repository %(repo)s" % config
		setup_new_repository( config['repo'] )
	configure_subversion( config )
	configure_trac( config )
	configure_apache( config )
	# Can the user setup usernames, etc via the web interface?

def do_teardown():
	print "Project Name:",
	name = raw_input()
	basename = name.lower().replace(' ','')
	repo = os.path.join( webbasedir, 'svn', basename )
	tracdir = os.path.join( webbasedir, 'trac', basename )
	for d in [repo,tracdir]:
		os.system( "rm -rf %s" % d )
		os.system( "rmdir `dirname %s`" % d )
	os.system( "rm /etc/httpd/conf.d/trac.conf" )
	# restore the trac.conf file.
	if os.path.isfile( "/etc/httpd/conf.d/trac.conf.orig" ):
		os.system( "cp /etc/httpd/conf.d/trac.conf.orig /etc/httpd/conf.d/trac.conf" )

if __name__ == "__main__":
	if len(sys.argv) <= 1:
		print "Need 'setup' or 'teardown' argument"
	elif sys.argv[1] == 'setup': do_setup()
	elif sys.argv[1] == 'teardown': do_teardown()
	else: print "error"

# vim:foldmethod=indent
# vim:foldcolumn=4
# vim:shiftwidth=4
# vim:ts=4
