#!/usr/bin/python

import argparse
import ConfigParser
import hubzero.utilities.misc
import os
import random
import re
import shutil
import string

sourceFilesDir = '/usr/lib/hubzero/cms'

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

def createHubzeroSecretsFile():
	"""
	We do this with prompts, so we don't run the risk of putting them on the command line
	"""
	
	print 'Enter MYSQL-ROOT password'
	mysqlrootpw = raw_input()

	print 'Enter LDAP-ADMIN password'
	ldapadminpw = raw_input()
	
	print 'Enter APPS password'
	appspw = raw_input()
	
	print 'Enter HUBREPO password'
	hubrepopw = raw_input()
	
	print 'Enter HUBDB password'
	hubdbpw = raw_input()
	
	print 'Enter JOOMLA-ADMIN password'
	jooomlaadminpw = raw_input()
	
	f = open('/etc/hubzero.secrets', 'w')
	f.write('MYSQL-ROOT=' + mysqlrootpw + '\n')
	f.write('LDAP-ADMIN=' + ldapadminpw  + '\n')
	f.write('APPS=' + appspw  + '\n')
	f.write('HUBREPO=' + hubrepopw  + '\n')
	f.write('HUBDB=' + hubdbpw  + '\n')
	f.write('JOOMLA-ADMIN=' + jooomlaadminpw  + '\n')
	f.close()

def createHubzeroConfigurationFile(hubname):

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

	cfgfile = open('/etc/hubzero.conf', 'w')
	config.write(cfgfile)
	

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


def writeInstallKey(filepath, fileOwner, fileGroup, providedKey=''):

	if not providedKey:
		installKey = ''.join(random.choice(string.ascii_lowercase + string.digits) for x in range(8))
	else:
		installKey = providedKey

	f = open(filepath, 'w')
	f.write("<?php\nclass JConfig {\n\n\tvar installkey = '" + installKey + "';\n\n}?>")
	f.close()

	hubzero.utilities.misc.exShellCommand(['chown', fileOwner + '.' + fileGroup, filepath])

	return(installKey)



# main

checkforroot()


# parse the command line
parser = argparse.ArgumentParser()
parser.add_argument('action', help='install/update')
parser.add_argument('sitename', help='sitename')
parser.add_argument('--docroot', help='root folder for the cms web files', default='/var/www')
parser.add_argument('--pwconfigure', help='create the /etc/hubzero.secrets file')
parser.add_argument('--siteconfigure', help='create the /etc/hubzero.conf file')
parser.add_argument('--upgrade', help='update an already installed hub. Skips configuration file generation. ')
parser.add_argument('--installkey', help='alphanumeric key used to run joomla install scripts, min length=8')
args = parser.parse_args()

# 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"
		exit(4)
	else:
		if len(args.installkey) < 8 :
			print "installkey must have length of at least 8"
			exit(5)
		else:
			print "installkey key ok"

if args.action == 'install':
	print 'Installing site named ' + args.sitename
elif args.action == 'update':
	print 'Updating not yet supported'
	exit(2)
else:
	print 'Not sure what we are doing'
	exit(3)


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'
	exit(2)

# check that docroot exists, if not, create it
installroot = args.docroot + "/" + args.sitename
#if not os.path.exists(installroot):
#	os.makedirs(installroot)

print "creating /etc/hubzero.secrets"
createHubzeroSecretsFile()

print "creating /etc/hubzero.conf"
installKey = createHubzeroConfigurationFile(args.sitename)

copyCMSFiles("/usr/share/hubzero-cms/cms/", installroot, wwwOwner, wwwGroup)


# Create the configuration.php file with the install key
if args.installkey:
	installKey = writeInstallKey(installroot + '/configuration.php', wwwOwner, wwwGroup, args.installkey)
else:
	installKey = writeInstallKey(installroot + '/configuration.php', wwwOwner, wwwGroup)


# Summary messages at end of install
print 'You installation key is: ' + installKey