import os, os.path, sys, shutil, re, getpass, urllib
import birchhome, customdoc, htmldoc, newuser, setplatform, update_local, BLHelper

##########
# Performs the tasks necessary for a complete installation of BIRCH
##########
# @param installDir the target location to install BIRCH
# @param logger the output log/console to use to display progress information
# @param adminEmail the administrator's email address to use for the installation
# @param install whether to install or update birch (true = install)
# @param minibirch whether to install miniBIRCH
##########
def run_pyinstall (PLATFORM, installDir, adminEmail, install, minibirch):
	username     = getpass.getuser()
	admindir     = os.path.join(installDir,   "admin"            )
	installBIRCH = os.path.join(installDir,   "install-scripts"    )
	local        = os.path.join(installDir,   "local"            )
	phtml        = os.path.join(installDir,   "public_html"      )
	scriptdir    = os.path.join(installDir,   "script"           )
	htmldirParam = os.path.join(installBIRCH, "htmldir.param"    )
	localgeneric = os.path.join(installDir,   "local-generic"    )
	oldstrParam  = os.path.join(installBIRCH, "oldstr.param"     )
	ladmin       = os.path.join(local,        "admin"            )
	pfile        = os.path.join(ladmin,       "BIRCH.properties" )
	paramfile    = os.path.join(ladmin,       "newstr.param"     )
	
	installDirURL = 'file://' + urllib.pathname2url(os.path.abspath(installDir))
	phtmlDirURL   = 'file://' + urllib.pathname2url(os.path.abspath(phtml))
	
        #---------------------- Steps for New Installation only ----------------------

        os.chdir(os.path.join(installDir, "install-scripts"))

	if install: 
	        print ('')
	        print ('')
	        print ("---------------------- NEW BIRCH INSTALLATION ----------------------")
		# create a new local directory for BIRCH
		print ("Moving local-generic to local")
		shutil.move(localgeneric, local)
	
		# write a new BIRCH.properties file
		print ("Writing BIRCH.properties")
		props = open (pfile, "w+")
		
		print >> props, "BirchProps.homedir=" + installDir
		print >> props, "BirchProps.adminUserid=" + username
		print >> props, "BirchProps.birchURL="  + phtmlDirURL
		print >> props, "BirchProps.adminEmail=" + adminEmail
		print >> props, "BirchProps.platform=" + PLATFORM
		# BirchProps.BirchMasterCopy
		print >> props, "BirchProps.birchHomeURL=" + installDirURL
		print >> props, "BirchProps.minibirch=" + str(minibirch)
		props.close()
	
		if os.path.exists(pfile):
			print ("Birch properties file written successfully")
		else:
			print ("Error, properties file not written!")

        #---------------------- Steps for Update only ----------------------
	else: # Update an existing installation
	        print ('')
	        print ('')
	        print ("---------------------- UPDATING BIRCH ----------------------")
		print ("Parsing BIRCH properties file")
		props = open (pfile, "r")
		for line in props:
			if '=' in line:
				fields = line.split('=')
				if fields[0].lower() == 'birchprops.adminemail':
					adminEmail = str(fields[1]).rstrip("\n\r")
		props.close()
		print ("Setting the BIRCH administrator's email to: " + adminEmail)

                # Turn off BIRCH access
                import nobirch
                nobirch.nobirch(installDir)

                # copy new files from local-generic to existing local directory

	        print ('')
	        print ("******************** update_local.py ********************")
                print ("Running update_local.py")
                update_local.update_local()

	props = None		
	
        #---------------------- Steps for both new install and update ----------------------
	# configure Birchhome
	print ('')
	print ('')
	print ('')
	print ("********************Birchhome********************")
	print ("Running birchhome")
	# need to update this once default install is using BIRCHDEV
	#	birchhome.main(install_dir,homepath);
	birchhome.birchhome(installDir)
	
	# need to run setplatform
	print ('')
	print ("********************Setplatform********************")
	print ("Setting birch platform to " + PLATFORM)
	print ("Using install dir: " + installDir)
	setplatform.setplatform(installDir)

	print ('')	
	print ("********************Customdoc********************")
	print ("Making paramfile for customdoc")
	pwriter = open(paramfile, "w+")

	# should be read from BIRCH.properties, just in case of update
	# this ensures that if BIRCH.properties does not work and the
	# install fails, we avoid problems further down the line.
	print >> pwriter, "~"
	print >> pwriter, phtmlDirURL
	print >> pwriter, installDirURL
	print >> pwriter, adminEmail
	print >> pwriter, installDir
	print >> pwriter, username
	pwriter.close()
	
	print ("Running customdoc.py")
	customdoc.customdoc(oldstrParam, paramfile, htmldirParam)

	print ('')
	print ("********************Htmldoc********************")
	print ("Running htmldoc.py")
	# htmldoc.htmldoc(installDir, PLATFORM)
	htmldoc.main()
	
	# RUN THE NEWUSER SCRIPT
        print ('')
	print ("********************Newuser********************")
	print ("Running newuser")
	newuser.newuser(installDir, PLATFORM)
	print ("Running newuser")

	# Get rid of the legacy install-birch directory, if it exists
        print ('')
        filename = os.path.join(installDir, "install-birch")
        if (os.path.exists(filename)) :
            print ("Deleting "  + filename)					
            shutil.rmtree(filename)

        print ('')
        print ('')
	print ("********************** birch_install DONE! *******************************")
	
if __name__=="__main__":
	if len(sys.argv) > 4:
		PLATFORM   = sys.argv[1]
		installDir = sys.argv[2]
		adminEmail = sys.argv[3]
		install    = (sys.argv[4].upper() == "Y")
		minibirch  = (sys.argv[5].upper() == "Y")
		
                if installDir.find("BIRCHDEV") > -1:
		    print ('>>> birch_install.py cannot be run in BIRCHDEV')
		    print ('>>> Doing so would clobber the master copy of BIRCH')
		    sys.exit(1)
                else: 
                    print ('')  
                    print ('===========================================================')
                    print ('|                                                         |') 
		    print ('|              Running birch_install.py                   |')
                    print ('|                                                         |')
                    print ('===========================================================')
		    run_pyinstall (PLATFORM, installDir, adminEmail, install, minibirch)
	else:
		print ("ERROR!!! INCORRECT NUMBER OF COMMAND LINE ARGUMENTS SPECIFIED!")
		print ("Usage: birch_install.py <platform> <install_dir> <admin_email> <installation (Y/N)> <minibirch (Y/N)>")
		sys.exit(1)
