#!/usr/bin/env python

import sys
import argparse
import ConfigParser
import hubzero.data.db
import hubzero.utilities.misc
import hubzero.utilities.user
import hubzero.config.webconfig
import os
import random
import re
import shutil
import string
import traceback
import distutils.dir_util

sourceFilesDir = "usr/lib/hubzero/cms"
hubzeroConfigFilePath = "/etc/hubzero.conf"

def checkforroot():
	uid = os.geteuid()
	if uid != 0:
		print 'Script must be run with root privileges'
		exit(1)

def generateAlphaNumPassword(length):
	pw = ''.join(random.choice(string.ascii_uppercase + string.ascii_lowercase + string.digits) for x in range(length-1)) + (random.choice(string.digits))	
	return pw

def createHubzeroSecretsFile(joomlaAdminPW):

	secretsFilename = "/etc/hubzero.secrets"

	# grab what we can when its stored, everything else is stored as hash and needs to be passed in
	hubdbpw = hubzero.config.webconfig.getWebConfigDBPassword()
	ldapadminpw = hubzero.config.webconfig.getComponentParam("com_system", "ldap_managerpw")

	f = open(secretsFilename, "w")
	f.write("[DEFAULT]\n")
	#f.write("LDAP-ADMIN=" + ldapadminpw  + "\n")
	#f.write("HUBREPO=" + hubrepopw  + "\n")
	f.write("HUBDB=" + hubdbpw  + "\n")
	f.write("JOOMLA-ADMIN=" + joomlaAdminPW  + "\n")
	f.close()

	hubzero.utilities.misc.exShellCommand(['chmod', "0600", secretsFilename])


def createHubzeroConfigurationFile(hubname, docroot):
	print "creating " + hubzeroConfigFilePath

	# For some reason, default section of the ini files can only be created via the constructor
	defaults = {'site':hubname}
	config = ConfigParser.ConfigParser(defaults)
	config.optionxform = str
	
	
	config.add_section(hubname)
	config.set(hubname, "HubName", hubname)
	config.set(hubname, "documentroot", docroot)

	cfgfile = open(hubzeroConfigFilePath, 'w')
	config.write(cfgfile)
	
	hubzero.utilities.misc.exShellCommand(['chown', '/etc/hubzero.conf', '0640'])


def deleteHubFromHubconfigFile(hubname):
	parser = ConfigParser.ConfigParser()
	parser.optionxform = str
	parser.read(hubzeroConfigFilePath)
	
	if parser.has_option(hubname, "documentroot"):
			parser.remove_section(hubname)

			# if this was the only hub, remove the file. If the removed hub was the default, reset the default hub
			if len(parser.sections()) < 1:
				os.remove(hubzeroConfigFilePath)
			else:

				#print (parser.sections())
				if parser.get("DEFAULT", "site") == hubname:
					newDefault = parser.sections()[0]
					parser.set("DEFAULT", "site", newDefault)
				
				cfgfile = open(hubzeroConfigFilePath, 'w')
				parser.write(cfgfile)
	

def insertHubIntoHubConfigFile(hubname, docroot, makeSiteDefault = False):
	"""
	config file /etc/hubzero.conf, a machine wide listing of hubs with the idea
	of supporting multiple hubs someday
	"""
	if not os.path.exists(hubzeroConfigFilePath):
		createHubzeroConfigurationFile(hubname, docroot)
	else:		
		parser = ConfigParser.RawConfigParser()
		parser.optionxform = str

		parser.read(hubzeroConfigFilePath)
		
		if not parser.has_option(hubname, docroot):
			parser.remove_section(hubname)
		
			parser.add_section(hubname)
			parser.set(hubname, "HubName", hubname)
			parser.set(hubname, "documentroot", docroot)
		
			if makeSiteDefault:
				parser.set("DEFAULT", "site", hubname)
		
			cfgfile = open(hubzeroConfigFilePath, 'w')
			parser.write(cfgfile)
	

def modifyHubConfigFile(sectionName, fieldName, fieldValue):
	"""
	Change a config value in the /etc/hubzero-cms/{hubname}.conf file for the specified section and field
	"""
	hubname = hubzero.config.webconfig.getDefaultSite()
	
	configFilename = "/etc/hubzero-cms/" + hubname + ".conf"
	parser = ConfigParser.RawConfigParser()
	parser.optionxform = str

	parser.read(configFilename)
	
	# make sure section exists, if not add it
	if not parser.has_section(sectionName):
		parser.add_section(sectionName)
			
	parser.set(sectionName, fieldName, fieldValue)	

	cfgfile = open(configFilename, 'w')
	parser.write(cfgfile)
	

def copyCMSFiles(src, dest, fileOwner, fileGroup):
	# Do the acutal copy
	distutils.dir_util.copy_tree(src, dest)
	# shutil.copytree(src, dest)
	
	# recursive set permissions
	hubzero.utilities.misc.exShellCommand(['chown', '-R', fileOwner + '.' + fileGroup, dest])


def createHubconfigurationPHPfile():
	""" Legacy, I know, but some things still use it """
	
	fileText="""<?php
class HubConfig {
 var $hubLDAPMasterHost = 'ldap://127.0.0.1';
 var $hubLDAPSlaveHosts = '';
 var $hubLDAPBaseDN = '%$hubLDAPBaseDN%';
 var $hubLDAPNegotiateTLS = '0';
 var $hubLDAPSearchUserDN = '%hubLDAPSearchUserDN%';
 var $hubLDAPSearchUserPW = '%hubLDAPSearchUserPW%';
 var $hubLDAPAcctMgrDN = '%hubLDAPAcctMgrDN%';
 var $hubLDAPAcctMgrPW = '%hubLDAPAcctMgrPW%';
 var $ipDBDriver = 'mysql';
 var $ipDBHost = '';
 var $ipDBPort = '';
 var $ipDBUsername = '';
 var $ipDBPassword = '';
 var $ipDBDatabase = '';
 var $ipDBPrefix = '';
 var $forgeName = '%HUBNAME% Forge';
 var $forgeURL = 'https://%HOSTNAME%';
 var $forgeRepoURL = 'https://%HOSTNAME%';
 var $svn_user = 'hubrepo';
 var $svn_password = '%FORGEPW%';
 var $hubzero_ipgeo_url = 'http://hubzero.org/ipinfo/v1';
 var $hubzero_ipgeo_key = '_HUBZERO_OPNSRC_V1_';
?>"""


	hubname = hubzero.config.webconfig.getDefaultSite()
	filePath = "/var/www/" + hubname + "/hubconfiguration.php"

	print "creating " + filePath
	
	# get hubrepo password from hubzero.secrets file, if file is not there, it's blank
	hubzeroSecretsFilename = "/etc/hubzero.secrets"
	if os.path.exists(hubzeroSecretsFilename):
		secretsConfig = ConfigParser.ConfigParser()
		secretsConfig.optionxform = str
		f1 = open(hubzeroSecretsFilename, "r")
		secretsConfig.readfp(f1)
		f1.close()
		
		if secretsConfig.has_option("DEFAULT", "HUBREPO"):
			forgePW = secretsConfig.get("DEFAULT", "HUBREPO")
		else:
			forgePW = ""
	else:
		forgePW = ""
		
	hubLDAPAcctMgrDN = hubzero.config.webconfig.getComponentParam("com_system", "ldap_managerdn")
	hubLDAPAcctMgrPW = hubzero.config.webconfig.getComponentParam("com_system", "ldap_managerpw")
	hubLDAPBaseDN = hubzero.config.webconfig.getComponentParam("com_system", "ldap_basedn")	
	hubLDAPSearchUserDN = hubzero.config.webconfig.getComponentParam("com_system", "ldap_searchdn")	
	hubLDAPSearchUserPW = hubzero.config.webconfig.getComponentParam("com_system", "ldap_searchpw")	

	rc, stdOut, StdErr = hubzero.utilities.misc.exShellCommand(["hostname", "--fqdn"])
	hostname = stdOut.strip()

	fileText = fileText.replace("%$hubLDAPBaseDN%", hubLDAPBaseDN)
	fileText = fileText.replace("%hubLDAPAcctMgrDN%", hubLDAPAcctMgrDN)
	fileText = fileText.replace("%hubLDAPAcctMgrPW%", hubLDAPAcctMgrPW)
	fileText = fileText.replace("%HOSTNAME%", hostname)
	fileText = fileText.replace("%FORGEPW%", forgePW)
	fileText = fileText.replace("%HUBNAME%", hubname)
	fileText = fileText.replace("%hubLDAPSearchUserDN%", hubLDAPSearchUserDN)
	fileText = fileText.replace("%hubLDAPSearchUserPW%", hubLDAPSearchUserPW)

	f1 = open(filePath, "w")
	f1.write(fileText)

	rc, procStdOut, procStdErr = hubzero.utilities.misc.exShellCommand(["chown", "www-data.www-data", filePath])	
	if rc: print procStdErr

	rc, procStdOut, procStdErr = hubzero.utilities.misc.exShellCommand(["chmod", "0644", filePath])	
	if rc: print procStdErr



def createHubConfigFile(hubname):
	"""home
	config file /etc/hubzero-cms/{hubname}.conf 
	"""
	
	print "creating /etc/hubzero-cms/" + args.hubname + ".conf"
	
	# For some reason, DEFAULT section of the ini files can only be created via the constructor
	defaults = {}
	config = ConfigParser.ConfigParser(defaults)
	config.optionxform = str
	
	config.add_section("global")
	config.set("global", "name", hubname)

	config.add_section("apache-config")
	config.set("apache-config", "document_root", "/var/www/" + hubname)
	config.set("apache-config", "force_canon", "false")
	config.set("apache-config", "enable_webdav", "false")
	config.set("apache-config", "enable_filexfer", "false")
	config.set("apache-config", "enable_subversion", "false")
	config.set("apache-config", "enable_trac", "false")
	config.set("apache-config", "enable_vncproxy", "false")

	config.add_section("mw")
	config.set("mw", "enable_mw", "false")

	filename = "/etc/hubzero-cms/" + hubname + ".conf"
	cfgfile = open(filename, 'w')
	config.write(cfgfile)
	
	hubzero.utilities.misc.exShellCommand(['chmod', filename, '0644'])

def deleteHubConfigFile(hubname):
	pass


def createDir(dirName, mode, owner, group):
	print "checking: " + dirName
	if not os.path.exists(dirName):
		print "creating " + dirName
		os.mkdir(dirName)
		hubzero.utilities.misc.exShellCommand(['chmod', mode, dirName])
		hubzero.utilities.misc.exShellCommand(['chown', owner + "." + group, dirName])


def checkDirectories(docroot):
	print "checking directories"
	
	createDir("/etc/hubzero-cms/", "0775", "root", "root")

	createDir("/var/log/hubzero-cms", "0775", "root", "www-data")
	createDir("/var/log/hubzero-cms/daily", "0770", "root", "www-data")
	createDir("/var/log/hubzero-cms/daily/imported", "0770", "root", "www-data")
	createDir("/var/log/hubzero-cms/archive", "0770", "root", "www-data")

	createDir("/var/log/apache2", "0750", "root", "adm")
	createDir("/var/log/apache2/daily", "0750", "root", "adm")
	createDir("/var/log/apache2/imported", "0750", "root", "adm")
	createDir("/var/log/apache2/archive", "0750", "root", "adm")

	createDir(docroot, "0775", "www-data", "www-data")

def m4Processing(inputFileName, outputFileName, m4ArgsArray, fileOwner, fileGroup, mode):

	commandArgsArray = ["m4"] + m4ArgsArray + [inputFileName]
	rc, procStdOut, procStdErr = hubzero.utilities.misc.exShellCommand(commandArgsArray)
	
	filename = outputFileName
	f = open(filename, 'w')
	f.write(procStdOut)
	f.close()
	hubzero.utilities.misc.exShellCommand(['chmod', "'" + str(mode) + "'", outputFileName])
	hubzero.utilities.misc.exShellCommand(['chown', fileOwner + '.' + fileGroup, outputFileName])

	
def mySQLDatabaseSetup(dbName, dbPW = ""):
	
	if dbPW == "":
		dbPW = generateAlphaNumPassword(10)
	
	print "Creating mySQL databases"

	# TODO SQL native calls for these
	# TODO check to see if database is running

	# primary database
	print "Creating database: " + dbName
	rc, procStdOut, procStdErr = hubzero.utilities.misc.exShellCommand(["/usr/bin/mysql", 
	    "--defaults-file=/etc/mysql/debian.cnf", 
	    "-e", "CREATE DATABASE " + dbName])
	if procStdOut: print procStdOut.strip()
	if rc : print procStdErr

	# metrics database
	print "Creating database: " + dbName + "-metrics"
	rc, procStdOut, procStdErr = hubzero.utilities.misc.exShellCommand(["/usr/bin/mysql", 
	    "--defaults-file=/etc/mysql/debian.cnf", 
	    "-e", "CREATE DATABASE " + dbName + "_metrics;"])
	if procStdOut: print procStdOut.strip()
	if rc : print procStdErr

	# Create user with full permissions
	print "Creating database user: " + dbName
	rc, procStdOut, procStdErr = hubzero.utilities.misc.exShellCommand(["/usr/bin/mysql", 
	    "--defaults-file=/etc/mysql/debian.cnf",
	    "-e", "GRANT ALL PRIVILEGES ON " + dbName + ".* TO " + dbName + "@localhost"])
	if procStdOut: print procStdOut.strip()
	if rc : print procStdErr

	print "Setting database password for user: " + dbName
	rc, procStdOut, procStdErr = hubzero.utilities.misc.exShellCommand(["/usr/bin/mysql", 
	    "--defaults-file=/etc/mysql/debian.cnf",
	    "-e", "SET PASSWORD FOR " + dbName + "@localhost = PASSWORD('" + dbPW + "'); flush privileges;"])
	if procStdOut: print procStdOut.strip()
	if rc : print procStdErr

	# return database host, database name, database username, and database pw
	# Most of these are known before this function call, but that could change
	return 'localhost', dbName, dbName, dbPW
	
	
def generateLogRotateFiles(hubname):
	
	sfilename = "/usr/share/hubzero-cms/conf/logrotate-cmsdebug.m4"
	tfilename = "/etc/logrotate.d/" + hubname + "-cmsdebug"
	print sfilename + " to " + tfilename
	m4Processing(sfilename, tfilename, ["-DHUBNAME=" + hubname], "root", "root", 0644)	

	sfilename = "/usr/share/hubzero-cms/conf/logrotate-cmsauth.m4"
	tfilename = "/etc/logrotate.d/" + hubname + "-cmsauth"
	print sfilename + " to " + tfilename
	m4Processing(sfilename, tfilename, ["-DHUBNAME=" + hubname], "root", "root", 0644)	
	
	sfilename = "/usr/share/hubzero-cms/conf/logrotate-hub-access.m4"
	tfilename = "/etc/logrotate.d/" + hubname + "-access"
	print sfilename + " to " + tfilename
	m4Processing(sfilename, tfilename, ["-DHUBNAME=" + hubname], "root", "root", 0644)	
	
	sfilename = "/usr/share/hubzero-cms/conf/logrotate-hub-error.m4"
	tfilename = "/etc/logrotate.d/" + hubname + "-error"
	print sfilename + " to " + tfilename
	m4Processing(sfilename, tfilename, ["-DHUBNAME=" + hubname], "root", "root", 0644)	
	

def generateApacheConfFiles(hubname):
	
	if not os.path.exists("/etc/apache2/sites-m4"):
		print "Creating /etc/apache2/sites-m4"
		createDir("/etc/apache2/sites-m4", "0755", "root", "root")
	
	# copy over the base template files
	print "Copying /usr/share/hubzero-cms/conf/hub.m4 to /etc/apache2/sites-m4/" + hubname + ".m4"
	hubzero.utilities.misc.exShellCommand(["cp", "/usr/share/hubzero-cms/conf/hub.m4", "/etc/apache2/sites-m4/" + hubname + ".m4"])
	hubzero.utilities.misc.exShellCommand(['chmod', "'", "/etc/apache2/sites-m4/" + hubname + ".m4"])
	hubzero.utilities.misc.exShellCommand(['chown', "root.root", "/etc/apache2/sites-m4/" + hubname + ".m4"])
	
	print "Copying /usr/share/hubzero-cms/conf/hub-ssl.m4 to /etc/apache2/sites-m4/" + hubname + "-ssl.m4"
	hubzero.utilities.misc.exShellCommand(["cp", "/usr/share/hubzero-cms/conf/hub-ssl.m4", "/etc/apache2/sites-m4/" + hubname + "-ssl.m4"])
	hubzero.utilities.misc.exShellCommand(['chmod', "0644", "/etc/apache2/sites-m4/" + hubname + "-ssl.m4"])
	hubzero.utilities.misc.exShellCommand(['chown', "root.root", "/etc/apache2/sites-m4/" + hubname + "-ssl.m4"])
	
	# do the M4 processing
	generateApacheM4config(hubname)
	

def generateApacheM4config(hubname):

	# Read the options from the /etc/hubzero-cms/{HUBNAME}.conf file to see what to enable in our apache config
	hubzeroCMSConfig = ConfigParser.ConfigParser()
	hubzeroCMSConfig.optionxform = str
	hubzeroCMSConfig.readfp(open("/etc/hubzero-cms/" + hubname + ".conf"))

	m4ApacheConfigOptions = []
	
	m4ApacheConfigOptions.append("-DHUBNAME=" + hubname)
	
	if hubzeroCMSConfig.get("apache-config", "force_canon").lower() == "true":
		m4ApacheConfigOptions.append("-DUSE_CANONICAL_HOSTNAME")
	
	if hubzeroCMSConfig.get("apache-config", "enable_webdav").lower() == "true":
		m4ApacheConfigOptions.append("-DUSE_WEBDAV")
	
	if hubzeroCMSConfig.get("apache-config", "enable_filexfer").lower() == "true":
		m4ApacheConfigOptions.append("-DUSE_FILEXFER")
		
	if hubzeroCMSConfig.get("apache-config", "enable_subversion").lower() == "true":
		m4ApacheConfigOptions.append("-DUSE_SUBVERSION")
	
	if hubzeroCMSConfig.get("apache-config", "enable_trac").lower() == "true":
		m4ApacheConfigOptions.append("-DUSE_TRAC")

	if hubzeroCMSConfig.get("apache-config", "enable_vncproxy").lower() == "true":
		
		dbPW = hubzero.config.webconfig.getWebConfigDBPassword()
		dbUserName = hubzero.config.webconfig.getWebConfigDBUsername()
		dbName = hubzero.config.webconfig.getWebConfigDBName()
		dbHost = hubzero.config.webconfig.getWebConfigOption("host")

		if dbHost: m4ApacheConfigOptions.append("-DDBHOST=" + dbHost)
		if dbUserName: m4ApacheConfigOptions.append("-DDBUSER=" + dbUserName)
		if dbPW: m4ApacheConfigOptions.append("-DDBPASS=" + dbPW)
		if dbName: m4ApacheConfigOptions.append("-DDBNAME=" + dbName)
		
		m4ApacheConfigOptions.append("-DUSE_VNCPROXY")
	
	basedn = hubLDAPBaseDN = hubzero.config.webconfig.getComponentParam("com_system", "ldap_basedn")
	if basedn: m4ApacheConfigOptions.append("-DBASEDN=" + basedn)

	ldap_searchdn = hubLDAPBaseDN = hubzero.config.webconfig.getComponentParam("com_system", "ldap_searchdn")
	if ldap_searchdn : m4ApacheConfigOptions.append("-DSEARCHDN=" + ldap_searchdn)

	ldap_searchpw = hubLDAPBaseDN = hubzero.config.webconfig.getComponentParam("com_system", "ldap_searchpw")
	if ldap_searchpw: m4ApacheConfigOptions.append("-DSEARCHPW=" + ldap_searchpw)

	if not os.path.exists("/etc/apache2/sites-m4"):
		print "/etc/apache2/sites-m4 doesn't exist, skipping m4 reconfiguration"	
	else:
		print "processing /etc/apache2/sites-m4/" + hubname + ".m4 to /etc/apache2/sites-available/" + hubname
		m4Processing("/etc/apache2/sites-m4/" + hubname + ".m4", 
		         "/etc/apache2/sites-available/" + hubname, 
		         m4ApacheConfigOptions, 
		         "root", "root", 0644)
	
		print "processing /etc/apache2/sites-m4/" + hubname + "-ssl.m4 to /etc/apache2/sites-available/" + hubname + "-ssl"
		m4Processing("/etc/apache2/sites-m4/" + hubname + "-ssl.m4", 
		         "/etc/apache2/sites-available/" + hubname + "-ssl", 
		         m4ApacheConfigOptions, 
		         "root", "root", 0644)
	

def loadSQLSchema(hubname, dbHost, dbName, dbUserName, dbPW, dbTablePrefix = 'jos_'):
	"""
	Load the hubzero schema sql and execute. Logic parses the file into individual statements
	"""
	
	dbsqlfile = open("/usr/share/hubzero-cms/cms/installation/sql/mysql/hubzero.sql", "r")
	dbsql = dbsqlfile.read()
	
	# split file into individual statementsstatements
	dbsql = re.sub("\n\#[^\n]*", "", "\n" + dbsql)

	sqlSplitter = re.compile("\n\n", re.MULTILINE)
	sqlStatements = sqlSplitter.split(dbsql)
	
	# execute each statement separately
	db = hubzero.data.db.mySql(dbHost, dbName, dbUserName, dbPW)	
	for sqlStatement in sqlStatements:
		if sqlStatement.strip() != "" :
			sqlStatement = string.replace(sqlStatement, "#__", dbTablePrefix)
			db.query_rowcount(sqlStatement, None)	


def loadSQLTableData(hubname, dbHost, dbName, dbUserName, dbPW, dbTablePrefix = 'jos_'):
	"""
	Load the hubzero sample data
	"""
	dbsqldatafile = open("/usr/share/hubzero-cms/cms/installation/sql/mysql/hz_sample_data.sql", "r")
	sql = dbsqldatafile.read()
	
	# replace the table prefixes
	sql = string.replace(sql, "#__", dbTablePrefix)
			
	db = hubzero.data.db.mySql(dbHost, dbName, dbUserName, dbPW)	
	db.query_rowcount(sql, None)
	

def createPHPConfigurationFile(hubname, docroot, dbName, dbPW, dbTablePrefix, siteAdminEmail, siteAdminName, mailFrom, installKey, fileOwner, fileGroup):
	"""
	Take the template and do all the needed replacements and write file to disk
	"""
	
	if not os.path.exists("/usr/share/hubzero-cms/cms/installation/template/tmpl/configuration.html"):
		print "cannot find /usr/share/hubzero-cms/cms/installation/template/tmpl/configuration.html"
		return 1
		
	configfile = open("/usr/share/hubzero-cms/cms/installation/template/tmpl/configuration.html", "r")
	configfileText =  configfile.read()
	configfile.close()
	
	# do all the replacements and substitutions
	configfileText = re.sub(re.compile("<jtmpl:comment>.*</jtmpl:comment>\n\n", re.MULTILINE | re.DOTALL), "", configfileText)
	configfileText = configfileText.replace('<jtmpl:tmpl name="configuration">', '')	
	configfileText = configfileText.replace('</jtmpl:tmpl>', "")	

	configfileText = configfileText.replace("{VAR_OFFLINE|addslashes}", "This site is down for maintenance. Please check back again soon.")
	configfileText = configfileText.replace("{VAR_SITENAME|addslashes}", hubname) # note this currently does TWO separate replacements
	configfileText = configfileText.replace("{VAR_DBTYPE|addslashes}", "mysql")
	configfileText = configfileText.replace("{VAR_DBHOSTNAME|addslashes}", "localhost")
	configfileText = configfileText.replace("{VAR_DBPASSWORD|addslashes}", dbPW)
	configfileText = configfileText.replace("{VAR_DBNAME|addslashes}", dbName)
	configfileText = configfileText.replace("{VAR_DBUSERNAME|addslashes}", hubname)
	configfileText = configfileText.replace("{VAR_DBPREFIX|addslashes}", dbTablePrefix)
	configfileText = configfileText.replace("{VAR_SECRET|addslashes}", generateAlphaNumPassword(10))
	configfileText = configfileText.replace("{VAR_HELPURL|addslashes}", "http://help.joomla.org")
	configfileText = configfileText.replace("{VAR_FTPHOST|addslashes}", "127.0.0.1")
	configfileText = configfileText.replace("{VAR_FTPPORT|addslashes}", "21")
	configfileText = configfileText.replace("{VAR_FTPUSER|addslashes}", "")
	configfileText = configfileText.replace("{VAR_FTPPASSWORD|addslashes}", "")
	configfileText = configfileText.replace("{VAR_FTPROOT|addslashes}", "")
	configfileText = configfileText.replace("{VAR_FTPENABLE|intval}", "0")
	configfileText = configfileText.replace("{VAR_ADMINEMAIL|addslashes}", mailFrom)
	configfileText = configfileText.replace("{VAR_METADESC|addslashes}", "Joomla! - the dynamic portal engine and content management system")
	configfileText = configfileText.replace("{VAR_METAKEYS|addslashes}", "joomla, Joomla")
	configfileText = configfileText.replace("{VAR_LOG_PATH|addslashes}", docroot + "/logs")
	configfileText = configfileText.replace("{VAR_TMP_PATH|addslashes}", docroot + "/tmp")

	configFilePath = docroot + "/configuration.php"

	configfile = open(configFilePath, 'w')
	configfile.write(configfileText)
	configfile.close()
	
	hubzero.utilities.misc.exShellCommand(['chmod', "0664", configFilePath])
	hubzero.utilities.misc.exShellCommand(['chown', fileOwner + "." + fileGroup, configFilePath])	
				
				
def reconfigureHub(args):
	print "regenerating m4 hub configuration files"
	generateApacheM4config(args.hubname)
	generateLogRotateFiles(args.hubname)


def installHub(args):
	
	hubname = args.hubname
	
	# we'll need the hostname in a couple of spots
	rc, stdOut, StdErr = hubzero.utilities.misc.exShellCommand(["hostname", "--fqdn"])
	hostname = stdOut.strip()
	
	# check the hubname
	p = re.compile("^[a-zA-Z][a-zA-Z0-9]+$")
	m = p.match(hubname)
	if not m:
		print "ERROR - install hubname must be alphanumeric and start with a letter"
		return(1)
	
	# docroot is where the www directory will go
	if not os.path.exists(args.docroot):
		print "ERROR - docroot (" + docroot + ") does not exist"
		return 1

	docroot = args.docroot + "/" + hubname
	
	if os.path.exists(docroot):
		print "ERROR - install location (" + docroot + ") already exists"
		return 1
	
	# if install key was provided, validate
	if args.installkey:
		p = re.compile("^[a-zA-Z0-9]+$")
		m = p.match(args.installkey)
	
		if not m:
			print "install key invalid - must be alphanumeric"
			return(1)
		else:
			if len(args.installkey) < 8 :
				print "installkey must have length of at least 8"
				return(1)
			else:
				print "installkey key ok"
	
	# Debian or RH?
	if hubzero.utilities.misc.isDebian():
		print "Debain install"
		wwwOwner = 'www-data'
		wwwGroup = 'www-data'
		
	if hubzero.utilities.misc.isRHEL():
		print "RHEL install"
		wwwOwner = 'apache'
	
	# Todo, offer upgrade functionality, for now, exit the install if the secrets file alread exists
	if os.path.exists('/etc/hubzero.secrets'):
		print 'looks like this is not a fresh install, /etc/hubzero.secrets file present'
		return(1)
	
	print "Copying CMS files from /usr/share/hubzero-cms/cms/ to " + docroot
	copyCMSFiles("/usr/share/hubzero-cms/cms/", docroot, wwwOwner, wwwGroup)

	print "Creating /etc/hubzero.conf entry"
	insertHubIntoHubConfigFile(hubname, docroot, True)

	# check various installation directories and create if necessary
	checkDirectories(docroot)
	
	# do substitutions for the configuraiton.php file from the template and write out
	print "creating configuration.php"
	dbPW = generateAlphaNumPassword(10)
	installKey = generateAlphaNumPassword(10)
	
	if args.mailfrom == "":
		args.mailfrom = "webmaster@" + hostname
	
	createPHPConfigurationFile(hubname, 
	                           docroot, 
	                           hubname, 
	                           dbPW, 
	                           args.dbprefix, 
	                           args.siteadminemail, 
	                           args.siteadminfirstname + ' ' + args.siteadminlastname,
	                           args.mailfrom,
	                           installKey,
	                           "www-data",
	                           "www-data")	
	
	createHubConfigFile(hubname)
	
	generateLogRotateFiles(hubname)

	# setup the databases
	print "Setting up the databases"
	dbHost, dbName, dbUserName, dbPW = mySQLDatabaseSetup(hubname, dbPW)
	
	print "Creating database schema"
	loadSQLSchema(hubname, "localhost", dbName, dbUserName, dbPW, args.dbprefix)
	
	print "Loading default data into database"
	loadSQLTableData(hubname, "localhost", dbName, dbUserName, dbPW, args.dbprefix)	

	# config apache
	print "enabling apache mod rewrite"
	rc, stdOut, StdErr = hubzero.utilities.misc.exShellCommand(["a2enmod", "rewrite"])
	print stdOut.strip()
	if rc: print stdErr
	
	print "enabling apache mod ssl"
	rc, stdOut, StdErr  = hubzero.utilities.misc.exShellCommand(["a2enmod", "ssl"])
	print stdOut.strip()
	if rc: print stdErr
	
	generateApacheConfFiles(hubname)

	# add joomla admin user
	if not args.promptsiteadminpw:
		adminpw = generateAlphaNumPassword(10)
	else:
		adminpw = pw = raw_input("Enter an password for your website admin user")

	# create home directory for the hub
	hubHomeDir = "/home/" + hubname
	print "creating " + hubHomeDir
	rc, stdOut, StdErr = hubzero.utilities.misc.exShellCommand(["mkdir", hubHomeDir])
	if stdOut: print stdOut.strip()
	if rc: print stdErr

	# create apache conf.d directory for the hub
	confDir = "/etc/apache2/" + hubname + ".conf.d";
	print "creating " + confDir
	rc, stdOut, StdErr = hubzero.utilities.misc.exShellCommand(["mkdir", confDir])
	if stdOut: print stdOut.strip()
	if rc: print stdErr
	rc, procStdOut, procStdErr = hubzero.utilities.misc.exShellCommand(["chown", "root:root", confDir])	
	if rc: 
		print procStdErr
	rc, procStdOut, procStdErr = hubzero.utilities.misc.exShellCommand(["chmod", "0755", confDir])	
	if rc: 
		print procStdErr

	# create hub admin account
	print "Adding site admin account"
	
	hubzero.utilities.user.addhubuser(args.hubname,
	                                  'admin', 
		                              args.siteadminfirstname + ' ' + args.siteadminlastname, 
		                              'webmaster@' + hostname,
		                              adminpw,
	                                  False,
		                              'Super Administrator', 
		                              25, 
		                              'users', 
		                              100, 
		                              1000,
	                                  '/bin/bash',
	                                  True,
	                                  '',
	                                  False,
		                              True)	
	
	#create /srv/hubname (www-data:www-data 0770)
	createDir("/srv/" + args.hubname, '0770', 'www-data', 'www-data')	

	#create /srv/hubname/projects (www-data:www-data 0770)
	createDir("/srv/" + args.hubname + "/projects", '0770', 'www-data', 'www-data')	
	
	#set the webpath parameter in params in the com_projects component entry to '/srv/hubname/projects'	
	hubzero.config.webconfig.addComponentParam('com_projects', 'webpath', '/srv/' + args.hubname + '/projects')
	
	print "restarting web server"
	rc, procStdOut, procStdErr = hubzero.utilities.misc.exShellCommand(["/etc/init.d/apache2", "restart"])	
	if rc: print procStdErr

	if args.createsecretsfile:
		createHubzeroSecretsFile(adminpw)

	# usr/bin/textifier exists enable textifier
	if os.path.exists("/usr/bin/textifier"):
		print "enabling textifier"
		textifierConfigure(True)
	
	# if mailgateway installed, enable mailgateway 
	if os.path.exists("/usr/lib/hubzero/bin/mailproc/mailproc.py"):
		print "enabling mailgateway"
		mailgateway(True)
		
	# Summary messages at end of install
	print "\nInstallation Complete"
	print "Your web docroot is: " + docroot
	print "Your database host is: " + dbHost
	print "Your database name is: " + dbName
	print "Your database username is: " + dbUserName
	print "Your database password is: " + dbPW
	print "Your installation key is: " + installKey
	print "Your web admin password is " + adminpw
	
	return(0)
	
	
def configHubFile(args):
	configFilename = "/etc/hubzero-cms/" + args.hubname + ".conf"

	if not os.path.exists(configFilename):
		print "Cannot find config file " + configFilename
		return(1)
	
	config = ConfigParser.RawConfigParser()
	config.optionxform = str
	config.read(configFilename)
	
	# = means we are setting, otherwise we're retrieving 
	if "=" in args.option:
		option, value = args.option.split("=")
		config.set(args.section, option, value)

		with open(configFilename, 'wb') as configfile:
			config.write(configfile)
	else:
		rv = config.get(args.section, args.option)
		print rv


def uninstallHub(args):
	hubname = args.hubname


	# reconcile /etc/hubzero.conf (remove hubname section, reassign default if it was set to value hubname)
	deleteHubFromHubconfigFile(hubname)

	if os.path.exists("/etc/hubzero-cms/" + hubname + ".conf"): os.remove("/etc/hubzero-cms/" + hubname + ".conf")
	if os.path.exists("/etc/logrotate.d/" + hubname + "-cmsauth"): os.remove("/etc/logrotate.d/" + hubname + "-cmsauth")
	if os.path.exists("/etc/logrotate.d/" + hubname + "-cmsdebug"): os.remove("/etc/logrotate.d/" + hubname + "-cmsdebug")
	if os.path.exists("/etc/logrotate.d/" + hubname + "-access"): os.remove("/etc/logrotate.d/" + hubname + "-access")
	if os.path.exists("/etc/logrotate.d/" + hubname + "-error"): os.remove("/etc/logrotate.d/" + hubname + "-error")
	if os.path.exists("/etc/apache2/sites-m4/" + hubname + ".m4"): os.remove("/etc/apache2/sites-m4/" + hubname + ".m4") 
	if os.path.exists("/etc/apache2/sites-available/" + hubname): os.remove("/etc/apache2/sites-available/" + hubname) 
	if os.path.exists("/etc/apache2/sites-m4/" + hubname + "-ssl.m4"): os.remove("/etc/apache2/sites-m4/" + hubname + "-ssl.m4")
	if os.path.exists("/etc/apache2/sites-available/" + hubname + "-ssl"): os.remove("/etc/apache2/sites-available/" + hubname + "-ssl")

	if os.path.exists("/etc/apache2/sites-enabled/" + hubname + "-ssl"):
		os.remove("/etc/apache2/sites-enabled/" + hubname + "-ssl")

	if os.path.exists("/etc/apache2/sites-enabled/" + hubname):
		os.remove("/etc/apache2/sites-enabled/" + hubname)
	
	print "You must manually delete /var/www/" + hubname
	print "You must manually delete /var/log/hubzero-cms/" + hubname + "-cmsdebug.log"
	print "You must manually delete /var/log/hubzero-cms/" + "hubname-cmsauth.log"
	print "You must manually delete /var/log/apache2/" + "hubname-access.log"
	print "You must manually delete /var/log/apache2/" + "hubname-error.log"

	# remove database user
	print "Removing database user: " + hubname
	rc, procStdOut, procStdErr = hubzero.utilities.misc.exShellCommand(["/usr/bin/mysql", 
        "--defaults-file=/etc/mysql/debian.cnf",
	    "-e", "DROP USER " + hubname + '@localhost'])
	if procStdOut: print procStdOut.strip()
	if rc : print procStdErr
	
	# remove databases
	print "Removing database: " + hubname
	rc, procStdOut, procStdErr = hubzero.utilities.misc.exShellCommand(["/usr/bin/mysql", 
        "--defaults-file=/etc/mysql/debian.cnf",
	    "-e", "DROP DATABASE " + hubname])
	if procStdOut: print procStdOut.strip()
	if rc : print procStdErr
	
	print "Removing database: " + hubname + "_metrics"
	rc, procStdOut, procStdErr = hubzero.utilities.misc.exShellCommand(["/usr/bin/mysql", 
        "--defaults-file=/etc/mysql/debian.cnf",
	    "-e", "DROP DATABASE " + hubname + "_metrics"])		
	print procStdOut
	if procStdOut: print procStdOut.strip()
	if rc : print procStdErr


def _ldapConfigure(args):
	ldapConfigure(args.enable)

def ldapConfigure(enable):
	print "ldap configure"

	if enable:
		print "Enabling ldap support"
		hubzero.config.webconfig.setPluginEnabled('user', 'ldap', True)
	else:
		print "Disabling ldap support"
		hubzero.config.webconfig.setPluginEnabled('user', 'ldap', False)


def _webdavConfigure(args):
	webdavConfigure(args.enable)

def webdavConfigure(enable):
	
	hubname = hubzero.config.webconfig.getDefaultSite()	
	filename = '/etc/auto.master'
	filename2 =  '/etc/auto.webdav'
	
	if enable:
		print "Enabling webdav"
		modifyHubConfigFile('apache-config', 'enable_webdav', 'true')

		print "editing /etc/auto.master"

		# add line to /etc/auto.master, remove any pre existing line similar to the one below (commented out or not) and add
		
		if not os.path.exists(filename):
			f1 = open(filename, 'w')
			f1.write("/webdav/home /etc/auto.webdav --timeout=60\n")
			f1.close()			
		else:
			f1 = open(filename, 'r')
			filetext = f1.read()
			f1.close()
			filetext = re.sub("^.*/webdav/home /etc/auto.webdav --timeout=60\n.*$", "", filetext, re.MULTILINE | re.DOTALL)
			filetext += "/webdav/home /etc/auto.webdav --timeout=60\n"
			
			f1 = open(filename, 'w')
			f1.write(filetext)
			f1.close()	
			
		print "Editing /etc/auto.webdav"
		f2 = open(filename2, 'w')
		f2.write("*  -fstype=usermap,user=www-data,source_user=&,allow_other :/home/" + hubname + "/&")
		f2.close()

	else:
		print "Disabling webdav"
		modifyHubConfigFile('apache-config', 'enable_webdav', 'false')

		f1 = open(filename, 'r')
		filetext = f1.read()
		f1.close()
		
		filetext = re.sub('^.*/webdav/home /etc/auto.webdav --timeout=60\n.*$', '', filetext)
		
		f1 = open(filename, 'w')
		f1.write(filetext)
		f1.close()
		
		print "removing " + filename2
		os.remove(filename2)
		

	# regenerate the apache config files to use the new option setting
	generateApacheM4config(hubname)
	
	print "restarting web server"
	rc, procStdOut, procStdErr = hubzero.utilities.misc.exShellCommand(["/etc/init.d/apache2", "restart"])	
	print procStdOut
	if rc: print procStdErr	
	
	print "restarting autofs"
	rc, procStdOut, procStdErr = hubzero.utilities.misc.exShellCommand(["/etc/init.d/autofs", "restart"])	
	print procStdOut
	if rc: print procStdErr	
		
		
def _tracConfigure(args):
	tracConfigure(args.enable)
		
def tracConfigure(enable):
	hubname = hubzero.config.webconfig.getDefaultSite()	
	
	if enable:
		print "Enabling trac"
		modifyHubConfigFile('apache-config', 'enable_trac', 'true')
		
		createDir("/opt/trac", "0770", "www-data", "www-data")
		createDir("/opt/trac/tools", "0770", "www-data", "www-data")		
		
	else:
		print "Disabling trac"
		modifyHubConfigFile('apache-config', 'enable_trac', 'false')

	# regenerate the apache config files to use the new option setting
	generateApacheM4config(hubname)

	print "restarting web server"
	rc, procStdOut, procStdErr = hubzero.utilities.misc.exShellCommand(["/etc/init.d/apache2", "restart"])	
	print procStdOut
	if rc: print procStdErr	


def _filexferConfigure(args):
	filexferConfigure(args.enable)
	
def filexferConfigure(enable):
	hubname = hubzero.config.webconfig.getDefaultSite()	

	if enable:
		print "Enabling trac"
		modifyHubConfigFile('apache-config', 'enable_filexfer', 'true')
	else:
		print "Disabling trac"
		modifyHubConfigFile('apache-config', 'enable_filexfer', 'false')

	# regenerate the apache config files to use the new option setting
	generateApacheM4config(hubname)
	
	print "restarting web server"
	rc, procStdOut, procStdErr = hubzero.utilities.misc.exShellCommand(["/etc/init.d/apache2", "restart"])	
	print procStdOut
	if rc: print procStdErr		


def _forcecanonConfigure(args):
	forcecanonConfigure(args.enable)

def forcecanonConfigure(args):
	hubname = hubzero.config.webconfig.getDefaultSite()	

	if args.enable:
		print "Enabling force_canon"
		modifyHubConfigFile('apache-config', 'force_canon', 'true')
	else:
		print "Disabling force_canon"
		modifyHubConfigFile('apache-config', 'force_canon', 'false')

	# regenerate the apache config files to use the new option setting
	generateApacheM4config(hubname)

	print "restarting web server"
	
	rc, procStdOut, procStdErr = hubzero.utilities.misc.exShellCommand(["/etc/init.d/apache2", "restart"])	
	print procStdOut
	if rc: print procStdErr	
	
def _forgeConfigure(args):
	forgeConfigure(args.enable)
	
def forgeConfigure(enable):
	
	hubname = hubzero.config.webconfig.getDefaultSite()	

	if enable:

		# subversion and track need to be enabled for this to work
		if hubzero.config.webconfig.getHubSiteConfig(hubname, "apache-config", "enable_trac").lower() != 'true':
			print "note: Forge requires both trac and subversion"
			tracConfigure(True)
			subversionConfigure(True)

		print "Enabling forge"
		
		modifyHubConfigFile('apache-config', 'enable_forge', 'true')
		
		filename = "/etc/sudoers.d/hubzero-forge"
		if not os.path.exists(filename):
			if not os.path.exists("/etc/sudoers.d"):
				os.makedirs("/etc/sudoers.d")
			
			f1 = open(filename, 'w')
			f1.write("www-data\tALL=(apps)NOPASSWD:/usr/bin/finalizetool\n")
			f1.write("www-data\tALL=(apps)NOPASSWD:/usr/bin/installtool\n")
			f1.write("www-data\tALL=(apps)NOPASSWD:/usr/bin/licensetool\n")
			f1.write("www-data\tALL=(root)NOPASSWD:/etc/init.d/apache2\n")	
			f1.close()			
		else:
			f1 = open(filename, 'r')
			filetext = f1.read()
			f1.close()

			# remove any possibly commented out lines then add the new lines
			filetext = re.sub(".*www-data\\s+ALL=\\(apps\\)NOPASSWD:/usr/bin/finalizetool\n", "", filetext, re.MULTILINE | re.DOTALL)
			filetext += "www-data\tALL=(apps)NOPASSWD:/usr/bin/finalizetool\n"

			filetext = re.sub(".*www-data\\s+ALL=\\(apps\\)NOPASSWD:/usr/bin/installtool\n", "", filetext, re.MULTILINE | re.DOTALL)
			filetext += "www-data\tALL=(apps)NOPASSWD:/usr/bin/installtool\n"

			filetext = re.sub(".*www-data\\s+ALL=\\(apps\\)NOPASSWD:/usr/bin/licensetool\n", "", filetext, re.MULTILINE | re.DOTALL)
			filetext += "www-data\tALL=(apps)NOPASSWD:/usr/bin/licensetool\n"
			
			filetext = re.sub(".*www-data\\s+ALL=\\(root\\)NOPASSWD:/etc/init.d/apache2\n", "", filetext, re.MULTILINE | re.DOTALL)
			filetext += "www-data\tALL=(root)NOPASSWD:/etc/init.d/apache2\n"

			f1 = open(filename, 'w')
			f1.write(filetext)
			f1.close()	

		rc, procStdOut, procStdErr = hubzero.utilities.misc.exShellCommand(["chmod", "0440", "-R", filename])	
		if rc: print procStdErr

		# add hubrepo password to hubzero.secrets file, if file is not there, not sure what to do, just skip for now
		hubzeroSecretsFilename = "/etc/hubzero.secrets"
		repoPW = dbPW = generateAlphaNumPassword(10)

		if os.path.exists(hubzeroSecretsFilename):
			secretsConfig = ConfigParser.ConfigParser()
			secretsConfig.optionxform = str
			f1 = open(hubzeroSecretsFilename, "rw")
			secretsConfig.readfp(f1)
			secretsConfig.set("DEFAULT", "HUBREPO", repoPW)
			f2 = open(hubzeroSecretsFilename, "w")
			secretsConfig.write(f2)
			f1.close()
			f2.close()
				
		# update hubrepo user passwords
		if hubzero.utilities.user.userExists('hubrepo'):
			hubzero.utilities.user.updateUserPW('hubrepo', repoPW)
			print "changing hubrepo pw on db and in ldap"
		else:
			print "no hubrepo user present in db, not changing password"

		# create the hubconfiguration.php file
		createHubconfigurationPHPfile()
		
	else:
		print "Disabling forge"
		modifyHubConfigFile('apache-config', 'enable_forge', 'false')

	# TODO	
	# error out if no ldap configured

	# regenerate the apache config files to use the new option setting
	generateApacheM4config(hubname)


def _subversionConfigure(args):
	subversionConfigure(args.enable)

def subversionConfigure(enable):
	hubname = hubzero.config.webconfig.getDefaultSite()	

	if enable:
		print "Enabling subversion"
		modifyHubConfigFile('apache-config', 'enable_subversion', 'true')
		createDir("/opt/svn", "0770", "www-data", "www-data")
		createDir("/opt/svn/tools", "0770", "www-data", "www-data")
		createDir("/etc/apache2/" + hubname + ".conf.d/svn", "0700", "apps", "apps")
		
	else:
		print "Disabling subversion for hub"
		modifyHubConfigFile('apache-config', 'enable_subversion', 'false')

	if os.path.exists("/etc/apache2/svn.conf") and os.path.exists("/etc/apache2/" + hubname + ".conf.d/svn"):
		print "Upgrading subversion for hub"
		print "Moving svn.conf to new /etc/apache2/" + hubname + ".conf.d/svn"
		createDir("/etc/apache2/" + hubname + ".conf.d/svn", "0700", "apps", "apps")
		os.rename("/etc/apache2/svn.conf", "/etc/apache2/" + hubname + ".conf.d/svn/svn.conf")
	if os.path.exists("/etc/apache2/svn.bak") and os.path.exists("/etc/apache2/" + hubname + ".conf.d/svn"):
		print "Upgrading subversion for hub"
		print "Moving svn.bak to new /etc/apache2/" + hubname + ".conf.d/svn"
		createDir("/etc/apache2/" + hubname + ".conf.d/svn", "0700", "apps", "apps")
		os.rename("/etc/apache2/svn.bak", "/etc/apache2/" + hubname + ".conf.d/svn/svn.bak")

	# regenerate the apache config files to use the new option setting
	generateApacheM4config(hubname)	
	
	print "restarting web server"
	rc, procStdOut, procStdErr = hubzero.utilities.misc.exShellCommand(["/etc/init.d/apache2", "restart"])	
	print procStdOut
	if rc: print procStdErr		


def _vncProxyConfigure(args):
	vncProxyConfigure(args.enable)

def vncProxyConfigure(enable):
	hubname = hubzero.config.webconfig.getDefaultSite()	

	if args.enable:
		print "Enabling vncproxy"
		modifyHubConfigFile('apache-config', 'enable_vncproxy', 'true')
	else:
		print "Disabling vncproxy"
		modifyHubConfigFile('apache-config', 'enable_vncproxy', 'false')

	# regenerate the apache config files to use the new option setting
	generateApacheM4config(hubname)	

	print "restarting web server"
	rc, procStdOut, procStdErr = hubzero.utilities.misc.exShellCommand(["/etc/init.d/apache2", "restart"])	
	print procStdOut
	if rc: print procStdErr	
	



def _mwServiceConfigure(args):
	mwServiceConfigure(args.enable)

def mwServiceConfigure(enable):
	hubname = hubzero.config.webconfig.getDefaultSite()	

	if enable:
		print "Enabling mw-service"
		# turn off disk quota
		vzConfFile = "/etc/vz/vz.conf"	
		print "Turning off disk quota in " + vzConfFile
		if os.path.exists(vzConfFile):
			with open(vzConfFile, "r") as f1:
				vzConfFileText = f1.read()
				
				# add or replace our needed config option
				if "DISK_QUOTA=yes" in vzConfFileText:
					vzConfFileText = vzConfFileText.replace("DISK_QUOTA=yes", "DISK_QUOTA=no")
				else:
					if not "DISK_QUOTA=no" in vzConfFileText:
						vzConfFileText += "DISK_QUOTA=no\n"
			
			print "Checking DISK_QUOTA=no in " + vzConfFile
			
			with open(vzConfFile, "w") as f1:
				f1.write(vzConfFileText)
		else:
			print vzConfFile + " not found"

		# some db work	
		dbPW = hubzero.config.webconfig.getWebConfigDBPassword()
		dbUserName = hubzero.config.webconfig.getWebConfigDBUsername()
		dbName = hubzero.config.webconfig.getWebConfigDBName()
		db =  hubzero.data.db.mySql("localhost", dbName, dbUserName, dbPW)		

		print "Doing mw database configuration"
	
		sql = "INSERT IGNORE INTO `host` VALUE ('localhost',14,'down',0,0);"
		db.query_rowcount(sql, None)	
	
		sql = "UPDATE `host` SET status='up' WHERE hostname='localhost';"
		db.query_rowcount(sql, None)	
		
		# add group 'network'
		if not hubzero.utilities.group.groupExists("network"):
			print "adding 'network' group"
			hubzero.utilities.group.addhubgroup("network", "network")
		else:
			print "'network' group already exists"
		
		
	else:
		pass


def _mwClientConfigure(args):
	mwClientConfigure(args.enable)

def mwClientConfigure(enable):
	hubname = hubzero.config.webconfig.getDefaultSite()	

	if enable:
		print "Enabling mw-client"
		
		modifyHubConfigFile('mw', 'enable_mw', 'true')		
	
		rc, procStdOut, procStdErr = hubzero.utilities.misc.exShellCommand(["mkdir", "-p", "/root/.ssh"])	
		if rc: print procStdErr
	
		# put key in root's authorized keys
		# cat /etc/mw-client/maxwell.key.pub >>  /root/.ssh/authorized_keys
		
		keyfile = "/etc/mw-client/maxwell.key.pub"
		authkeysfile = "/root/.ssh/authorized_keys"
		
		f1 = open(keyfile, 'r')
		key = f1.read()
		f1.close()
		
		# add to file
		if os.path.exists(authkeysfile):
		
			f2 = open(authkeysfile, 'r')
			keyfileTextOriginal = f2.read()
			f2.close()
			
			if not key in keyfileTextOriginal:
				print "adding /etc/mw-client/maxwell.key.pub to /root/.ssh/authorized_keys"
				keyfile = open("/root/.ssh/authorized_keys", "a")
				keyfile.write(key)
				keyfile.close()
			else:
				print "key already in /root/.ssh/authorized_keys"

		else: # create file
			print "adding /etc/mw-client/maxwell.key.pub to newly created /root/.ssh/authorized_keys file"
			keyfile = open("/root/.ssh/authorized_keys", "w")
			keyfile.write(key)
			keyfile.close()			
			
		# generate /etc/mw-client/mw-client.conf	
		# get hub template
		dbPW = hubzero.config.webconfig.getWebConfigDBPassword()
		dbUserName = hubzero.config.webconfig.getWebConfigDBUsername()
		dbName = hubzero.config.webconfig.getWebConfigDBName()
		db =  hubzero.data.db.mySql("localhost", dbName, dbUserName, dbPW)		
		sql = 'select template from `jos_templates_menu` where menuid = 0 and client_id=0'
		template = db.execSelectQueryScalar(sql, None)			

		# do /etc/mw-client/mw-clienta.conf file replacements
		# get hostname
		rc, procStdOut, procStdErr = hubzero.utilities.misc.exShellCommand(["hostname", "--fqdn"])	
		if rc: 
			print procStdErr
			hostname = 'unknown'
		else: 
			hostname  = procStdOut.strip()
		
		maxwellConfFileText = (
	    "mysql_host = \"localhost\"\n"
	    "mysql_user=\"" + hubname + "\"\n"
	    "mysql_password=\"" + hubzero.config.webconfig.getWebConfigOption('password') + "\"\n"
	    "mysql_db=\"" + hubname + "\"\n"
	    "hub_name=\"" + hubname + "\"\n"
	    "hub_url=\"http://" + hostname + "/\"\n"
	    "hub_homedir=\"/home/" + hubname + "\"\n"
	    "hub_template=\"" + template + "\"\n")
		
		
		confFileName = "/etc/mw-client/mw-client.conf"
		# write the file
		print "creating " + confFileName
		f3 = open(confFileName, "w")
		f3.write(maxwellConfFileText)
		f3.close()

		rc, procStdOut, procStdErr = hubzero.utilities.misc.exShellCommand(["chown", "root.www-data", confFileName])	
		if rc: 
			print procStdErr

		rc, procStdOut, procStdErr = hubzero.utilities.misc.exShellCommand(["chmod", "0640", confFileName])	
		if rc: 
			print procStdErr
			
		#restart /etc/init.d/expire-sessions
		if os.path.exists("/etc/init.d/expire-sessions"):
			rc, procStdOut, procStdErr = hubzero.utilities.misc.exShellCommand(["/etc/init.d/expire-sessions", "restart"])
			if rc: print procStdErr
		else:
			print "/etc/init.d/expire-sessions not restarted, file not found"
	
	else:
		print "Disabling mw for hub"
		modifyHubConfigFile('mw', 'enable_mw', 'false')		
		
		
		
def _textifierConfigure(args):
	textifierConfigure(args.enable)
	
def textifierConfigure(enable):
	
	confFileText = """host: localhost
db: %db
user: %user
password: %password
insert: INSERT INTO jos_document_text_data(hash, body) VALUES (%0q,%1q) ON DUPLICATE KEY UPDATE body = %1q
"""	
	if enable:
		dbPW = hubzero.config.webconfig.getWebConfigDBPassword()
		dbUserName = hubzero.config.webconfig.getWebConfigDBUsername()
		dbName = hubzero.config.webconfig.getWebConfigDBName()
		
		confFileText = confFileText.replace("%db", dbName)
		confFileText = confFileText.replace("%user", dbUserName)
		confFileText = confFileText.replace("%password", dbPW)
		
		# create /etc/textifier.conf
		textifierConfFile = "/etc/textifier.conf"
		
		file1 = open(textifierConfFile, "w")
		file1.write(confFileText)	
		os.chmod(textifierConfFile, 0640)

		hubzero.utilities.misc.exShellCommand(['chown', 'www-data.www-data', textifierConfFile])
	
def _mwMetrics(args):
	mwMetrics(args.enable)
	
def mwMetrics(enable):
	if enable:
		# some db work
		
		dbPW = hubzero.config.webconfig.getWebConfigDBPassword()
		dbUserName = hubzero.config.webconfig.getWebConfigDBUsername()
		dbName = hubzero.config.webconfig.getWebConfigDBName()
		db =  hubzero.data.db.mySql("localhost", dbName, dbUserName, dbPW)		

		print "Doing metrics database configuration"
	
		sql = 'UPDATE jos_plugins SET published = 0 WHERE folder = "usage";'
		db.query_rowcount(sql, None)	
	
		sql = 'UPDATE jos_plugins SET published = 1 WHERE folder = "usage" AND element IN ("overview","maps")'
		db.query_rowcount(sql, None)			
		
		sql = 'UPDATE jos_plugins SET params = "period=14 nchart_path=/site/stats/chart_resources/ nmap_path=/site/stats/resource_maps/" WHERE folder = "resources" AND element = "usage";'
		db.query_rowcount(sql, None)			

		sql = 'UPDATE jos_resource_types SET params="plg_citations=1nplg_questions=1nplg_recommendations=1nplg_related=1nplg_reviews=1nplg_usage=1nplg_versions=1nplg_favorite=1nplg_share=1nplg_wishlist=1nplg_supportingdocs=1" WHERE type="Tools"'
		db.query_rowcount(sql, None)			
		
	else:
		pass


def _mailgateway(args):
	mailgateway(args.enable)

def mailgateway(enable):

	if enable:

		pwSalt = generateAlphaNumPassword(16)
		pw = generateAlphaNumPassword(16)
		dbPW = hubzero.config.webconfig.getWebConfigDBPassword()
		dbUserName = hubzero.config.webconfig.getWebConfigDBUsername()
		dbName = hubzero.config.webconfig.getWebConfigDBName()
		confFileName = "/etc/hubmail_gw.conf"
		hubname = hubzero.config.webconfig.getDefaultSite()

		rc, stdOut, StdErr = hubzero.utilities.misc.exShellCommand(["hostname", "--fqdn"])
		hostname = stdOut.strip()

		fileText = """<?php
class HubmailConfig {
 public $user = '%DBUSER%';
 public $password = '%DBPW%';
 public $db = '%DBNAME%';
 public $host = 'localhost';
 public $fromname = '%HUBNAME% Support Team';
 public $mailfrom = 'support@%HOSTNAME%';
 public $sitename = '%HUBNAME%';
 public $email_token_current_version = '1';
 public $email_token_encryption_info_v1 = '%SALT%,%PW%';
 public $hubShortURL = '%HOSTNAME%';
 public $hubLongURL = 'http://%HOSTNAME%';
}
"""
		fileText = fileText.replace("%DBUSER%", dbUserName)
		fileText = fileText.replace("%DBPW%", dbPW)
		fileText = fileText.replace("%DBNAME%", dbName)
		fileText = fileText.replace("%HUBNAME%", hubname)
		fileText = fileText.replace("%HOSTNAME%", hostname)
		fileText = fileText.replace("%SALT%", pwSalt)
		fileText = fileText.replace("%PW%", pw)
	
		with open(confFileName, "w") as f1:
			f1.write(fileText)
	
		rc, procStdOut, procStdErr = hubzero.utilities.misc.exShellCommand(["chown", "www-data.Debian-exim", confFileName])	
		if rc: 
			print procStdErr
	
		rc, procStdOut, procStdErr = hubzero.utilities.misc.exShellCommand(["chmod", "0640", confFileName])	
		if rc: 
			print procStdErr

	else:
		pass
	

def _submitserverConfigure(args):
	submitserverConfigure(args.enable)
	
def submitserverConfigure(enable):

	confFileName = "/etc/submit/submit-server.conf"

	fileText = """# WARNING: this file is auto-generated.

listenURIs = tcp://:830

mysqlHost = localhost
mysqlUser = %DBUSERNAME%
mysqlPassword = %DBPW%
mysqlDB = %DBNAME%

ldapHosts = ldap://localhost
ldapBaseDN = %hubLDAPBaseDN%
ldapUserDN = uid=%s,ou=users,%hubLDAPBaseDN%

loadLimit = 510         # cumulative load must not exceed 510
loadHalflife = 3600     # static load is divided in half ever 3600 sec
loadHorizon = 86400     # forget about jobs started earlier than 1 day ago
"""

	if enable:
		dbPW = hubzero.config.webconfig.getWebConfigDBPassword()
		dbUserName = hubzero.config.webconfig.getWebConfigDBUsername()
		dbName = hubzero.config.webconfig.getWebConfigDBName()
		hubname = hubzero.config.webconfig.getDefaultSite()
		hubLDAPAcctMgrDN = hubzero.config.webconfig.getComponentParam("com_system", "ldap_managerdn")
		hubLDAPAcctMgrPW = hubzero.config.webconfig.getComponentParam("com_system", "ldap_managerpw")
		hubLDAPBaseDN = hubzero.config.webconfig.getComponentParam("com_system", "ldap_basedn")	

		rc, stdOut, StdErr = hubzero.utilities.misc.exShellCommand(["hostname", "--fqdn"])
		hostname = stdOut.strip()

		if not hubzero.utilities.group.groupExists("submit"):
			print "adding 'submit' group"
			hubzero.utilities.group.addhubgroup("submit", "submit")
		else:
			print "'submit' group already exists"

		fileText = fileText.replace("%DBUSERNAME%", dbUserName)
		fileText = fileText.replace("%DBPW%", dbPW)
		fileText = fileText.replace("%DBNAME%", dbName)
		fileText = fileText.replace("%hubLDAPBaseDN%", hubLDAPBaseDN)
		fileText = fileText.replace("%hubLDAPAcctMgrDN%", hubLDAPAcctMgrDN)
		fileText = fileText.replace("%hubLDAPBaseDN%", hubLDAPBaseDN)


		if not os.path.exists("/etc/submit/"):
			os.makedirs("/etc/submit/")
		with open(confFileName, "w") as f1:
			f1.write(fileText)

		#rc, procStdOut, procStdErr = hubzero.utilities.misc.exShellCommand(["chown", "XXX.XXX", confFileName])	
		#if rc: 
		#	print procStdErr
	
		rc, procStdOut, procStdErr = hubzero.utilities.misc.exShellCommand(["chmod", "0640", confFileName])	
		if rc: 
			print procStdErr

	
def _createDHCPExitHookFile(args):
	fileName = "/etc/dhcp/dhclient-exit-hooks.d/dhcpleaseupdate"
	fileText = """# our custom change is delimited by #.# ... #.#
# just delete this and replace it every time
sed -i "/\#\.\#/,/\#\.\#/d" /etc/hosts

hn=$(hostname)
fqdn=$(hostname -f)
date=`date`

line="$new_ip_address $fqdn $hn"
t="#.# Do not edit. Auto inserted section by /etc/dhcp/dhclient-exit-hooks.d/dhcpleaseupdate script on $date \\n$line\\n#.#"

sed -i "1i $t" /etc/hosts"""

	if args.enable:
		with open(fileName, "w") as f1:
			f1.write(fileText)
			
		rc, procStdOut, procStdErr = hubzero.utilities.misc.exShellCommand(["chmod", "0644", fileName])	
		if rc: print procStdErr
			
	else:
		if os.path.exists(fileName):
			os.remove(fileName)


def updateHub(args):

	# Debian or RH?
	if hubzero.utilities.misc.isDebian():
		wwwOwner = 'www-data'
		wwwGroup = 'www-data'
		
	if hubzero.utilities.misc.isRHEL():
		wwwOwner = 'apache'
	

	hubname = hubzero.config.webconfig.getDefaultSite()
        docroot = hubzero.config.hubzerositeconfig.getHubzeroConfigOption(hubname, "DocumentRoot")

	if not os.path.exists(docroot + "/.git"):
		print "Copying CMS files from /usr/share/hubzero-cms/cms/ to " + docroot
		copyCMSFiles("/usr/share/hubzero-cms/cms/", docroot, wwwOwner, wwwGroup)
	else:
		print "Leaving git controlled CMS files alone"

	if os.path.exists("/etc/apache2/sites-m4"):
		generateApacheConfFiles(hubname)

	if hubzero.config.webconfig.getHubSiteConfig(hubname, "apache-config", "enable_svn").lower() == 'true':
		subversionConfigure(True)
	else:
		subversionConfigure(False)

# ####################################################################################
# main

# we'll need the hostname in a couple of spots
rc, stdOut, StdErr = hubzero.utilities.misc.exShellCommand(["hostname", "--fqdn"])
if rc: print StdErr
hostname = stdOut	

# exit if not being run by the root user
checkforroot()

# main parser
parser = argparse.ArgumentParser(prog="hzcms")
subparsers = parser.add_subparsers()

# config subcommand
parser_config = subparsers.add_parser('confighubfile', help='get and set config values for a hub')
parser_config.add_argument('hubname', help='hubname')
parser_config.add_argument('section', help='section name')
parser_config.add_argument('option', help='option name')
parser_config.set_defaults(func=configHubFile)

# install subcommand
parser_install = subparsers.add_parser('install', help='install a new hub')
parser_install.add_argument('hubname', help='name of new hub')
parser_install.add_argument('--dbprefix', help='prefix for web tables', default='jos_')
parser_install.add_argument('--docroot', help='root folder for the cms web files', default='/var/www')
parser_install.add_argument('--installkey', help='alphanumeric key used to run joomla install scripts, min length=8')
parser_install.add_argument('--mailfrom', help='email of the site admin', default="")
parser_install.add_argument('--promptsiteadminpw', help='prompt for a site admin password, if not provided, one will be created and output to screen', action="store_true", default=False)
parser_install.add_argument('--createsecretsfile', help='create the /etc/hubzero.secrets file', default=True, action="store_true")
parser_install.add_argument('--siteadminemail', help='email of the site admin', default='admin@myhub.org')
parser_install.add_argument('--siteadminfirstname', help='name of the site admin', default="Site")
parser_install.add_argument('--siteadminlastname', help='name of the site admin', default="Administrator")
parser_install.set_defaults(func=installHub)

# uninstall subcommand
parser_uninstall = subparsers.add_parser('uninstall', help='remove existing hub')
parser_uninstall.add_argument('hubname', help='name of hub to delete')
parser_uninstall.set_defaults(func=uninstallHub)

# update subcommand
parser_update = subparsers.add_parser('update', help='update existing hub')
parser_update.set_defaults(func=updateHub)

# reconfigure subcommand
#parser_reconfigure = subparsers.add_parser('reconfigure', help='regenerate m4 configfiles for existing hub')
#parser_reconfigure.add_argument('hubname', help='hubname')
#parser_reconfigure.set_defaults(func=reconfigureHub)

# OK, time to make head spin by digging down two subparsers, the configure subparser will have multiple subparsers
parser_configure = subparsers.add_parser('configure', help='various configuration commands')
parser_configure_subparsers = parser_configure.add_subparsers()

# configure/ldap subcommand
parser_configure_ldap = parser_configure_subparsers.add_parser('ldap', help='configure hub ldap')
group = parser_configure_ldap.add_mutually_exclusive_group()
group.add_argument('--enable', dest='enable', help='turn on ldap plugin for hub', action="store_true", default=True)
group.add_argument('--disable', dest='enable', help='turn off ldap plugin for hub', action="store_false", default=False)
parser_configure_ldap.set_defaults(func=ldapConfigure)

# configure/webdav subcommand
parser_configure_webdav = parser_configure_subparsers.add_parser('webdav', help='configure hub webdav')
group = parser_configure_webdav.add_mutually_exclusive_group()
group.add_argument('--enable', dest='enable', help='turn on webdav functionality for hub', action="store_true", default=True)
group.add_argument('--disable', dest='enable', help='turn off webdav functionality for hub', action="store_false", default=False)
parser_configure_webdav.set_defaults(func=webdavConfigure)

# configure/subversion
parser_configure_subversion = parser_configure_subparsers.add_parser('subversion', help='configure hub ')
group = parser_configure_subversion.add_mutually_exclusive_group()
group.add_argument('--enable', dest='enable', help='turn on subversion functionality for hub', action="store_true", default=True)
group.add_argument('--disable', dest='enable', help='turn off subversion functionality for hub', action="store_false", default=False)
parser_configure_subversion.set_defaults(func=_subversionConfigure)

# configure/filexfer
parser_configure_filexfer = parser_configure_subparsers.add_parser('filexfer', help='configure hub filexfer')
group = parser_configure_filexfer.add_mutually_exclusive_group()
group.add_argument('--enable', dest='enable', help='turn on filexfer functionality for hub', action="store_true", default=True)
group.add_argument('--disable', dest='enable', help='turn off filexfer functionality for hub', action="store_false", default=False)
parser_configure_filexfer.set_defaults(func=filexferConfigure)

# configure/forcecnanno
parser_configure_forcecanon = parser_configure_subparsers.add_parser('forcecanon', help='configure hub forcecanon')
group = parser_configure_forcecanon.add_mutually_exclusive_group()
group.add_argument('--enable', dest='enable', help='turn on forcecanon functionality for hub', action="store_true", default=True)
group.add_argument('--disable', dest='enable', help='turn off forcecanon functionality for hub', action="store_false", default=False)
parser_configure_forcecanon.set_defaults(func=forcecanonConfigure)

# configure/forge
parser_configure_forge = parser_configure_subparsers.add_parser('forge', help='configure hub forge')
group = parser_configure_forge.add_mutually_exclusive_group()
group.add_argument('--enable', dest='enable', help='turn on forge functionality for hub', action="store_true", default=True)
group.add_argument('--disable', dest='enable', help='turn off forge functionality for hub', action="store_false", default=False)
parser_configure_forge.set_defaults(func=_forgeConfigure)


# configure/hostsupdate
parser_configure_hosts = parser_configure_subparsers.add_parser('hosts', help='installs hook to auto update /etc/hosts to include hostname for host IP obtained from DHCP (only matters in VM/DHCP installs)')
group = parser_configure_hosts.add_mutually_exclusive_group()
group.add_argument('--enable', dest='enable', help='turn on forge functionality for hub', action="store_true", default=True)
group.add_argument('--disable', dest='enable', help='turn off forge functionality for hub', action="store_false", default=False)
parser_configure_hosts.set_defaults(func=_createDHCPExitHookFile)



# configure/mailgateway
parser_configure_mailgateway = parser_configure_subparsers.add_parser('mailgateway', help='configure hub metrics')
group = parser_configure_mailgateway.add_mutually_exclusive_group()
group.add_argument('--enable', dest='enable', help='turn on mailgateway functionality for hub', action="store_true", default=True)
group.add_argument('--disable', dest='enable', help='turn off mailgateway functionality for hub', action="store_false", default=False)
parser_configure_mailgateway.set_defaults(func=_mailgateway)

# configure/metrics
parser_configure_metrics = parser_configure_subparsers.add_parser('metrics', help='configure hub metrics')
group = parser_configure_metrics.add_mutually_exclusive_group()
group.add_argument('--enable', dest='enable', help='turn on metrics functionality for hub', action="store_true", default=True)
group.add_argument('--disable', dest='enable', help='turn off metrics functionality for hub', action="store_false", default=False)
parser_configure_metrics.set_defaults(func=_mwMetrics)

# configure/mw-client
parser_configure_mwclient = parser_configure_subparsers.add_parser('mw-client', help='configure hub mw-client')
group = parser_configure_mwclient.add_mutually_exclusive_group()
group.add_argument('--enable', dest='enable', help='turn on mw-client functionality for hub', action="store_true", default=True)
group.add_argument('--disable', dest='enable', help='turn off mw-client functionality for hub', action="store_false", default=False)
parser_configure_mwclient.set_defaults(func=_mwClientConfigure)

# configure/_mw-service
parser_configure_mwservice = parser_configure_subparsers.add_parser('mw-service', help='configure hub mw-service')
group = parser_configure_mwservice.add_mutually_exclusive_group()
group.add_argument('--enable', dest='enable', help='turn on mw-service functionality for hub', action="store_true", default=True)
group.add_argument('--disable', dest='enable', help='turn off mw-service functionality for hub', action="store_false", default=False)
parser_configure_mwservice.set_defaults(func=_mwServiceConfigure)

# configure/submit-server
parser_configure_submitserver = parser_configure_subparsers.add_parser('submit-server', help='configure hub submit server')
group = parser_configure_submitserver.add_mutually_exclusive_group()
group.add_argument('--enable', dest='enable', help='turn on submit server functionality for hub', action="store_true", default=True)
group.add_argument('--disable', dest='enable', help='turn off submit server functionality for hub', action="store_false", default=False)
parser_configure_submitserver.set_defaults(func=_submitserverConfigure)

# configure/textifier
parser_configure_textifier = parser_configure_subparsers.add_parser('textifier', help='configure hub textifier')
group = parser_configure_textifier.add_mutually_exclusive_group()
group.add_argument('--enable', dest='enable', help='turn on textifier functionality for hub', action="store_true", default=True)
group.add_argument('--disable', dest='enable', help='turn off textifier functionality for hub', action="store_false", default=False)
parser_configure_textifier.set_defaults(func=_textifierConfigure)

# configure/trac
parser_configure_trac = parser_configure_subparsers.add_parser('trac', help='configure hub trac')
group = parser_configure_trac.add_mutually_exclusive_group()
group.add_argument('--enable', dest='enable', help='turn on trac functionality for hub', action="store_true", default=True)
group.add_argument('--disable', dest='enable', help='turn off trac functionality for hub', action="store_false", default=False)
parser_configure_trac.set_defaults(func=_tracConfigure)

# configure/vncproxy
parser_configure_vncproxy = parser_configure_subparsers.add_parser('vncproxy', help='configure hub vncproxy')
group = parser_configure_vncproxy.add_mutually_exclusive_group()
group.add_argument('--enable', dest='enable', help='turn on vncproxy functionality for hub', action="store_true", default=True)
group.add_argument('--disable', dest='enable', help='turn off vncproxy functionality for hub', action="store_false", default=False)
parser_configure_vncproxy.set_defaults(func=_vncProxyConfigure)

# call subcommand
args =  parser.parse_args()
args.func(args)
