'''
Copyright (C) 2016 OpenText Corporation
'''
import platform
import os, stat
if os.name != "posix": 
	import ctypes
else:
	import pwd
import tarfile
import zipfile
import sys, errno
import re
import subprocess
import shutil, glob
from distutils.sysconfig import get_python_lib
from time import strftime as date

try:
	import pstats
except:
	print "ERROR: pstats could not be imported."
	print "Please install python-profiler using:"
	print "sudo apt-get install python-profiler"
	sys.exit(1)

if os.name == 'posix':
	acceptLicense = raw_input('I accept the attached FirstClass End User License Agreement (yes/no):')
	if 'yes' not in acceptLicense:
		sys.exit(1)
	
pthChar = os.sep

#Environment Variables 
#FCWS_WebServerConfig (cherrypy or apache)
#FCWS_Python_Lib (additional dir to search for installed fcws package)
#FCWS_Apache_Conf  (directory housing httpd.conf files)

platformLabels = {"Darwin":"osx","Linux":"linux","Windows":"win"}
platform = platformLabels[platform.system()]
pythonpth = sys.executable
libPthList=[get_python_lib(),get_python_lib(plat_specific=1),get_python_lib(standard_lib=1),get_python_lib(plat_specific=1,standard_lib=1)]

if os.getenv('FCWS_Python_Lib'):
	libPthList.insert(0,os.getenv('FCWS_Python_Lib'))
	
sitePackagesPath= get_python_lib()

installDir = None
PackageLocation = None
mypackagepth = None
myPackageName = None
pkgArchive = None
symlink = True
installDirName = "FirstClass Web Services"
archiveDirName = "PkgArchives"
Install_setupTools=False
ts = date('%Y-%m-%d_%H%M%S')
currentPkgMajorVersion=None
newPkgMajorVersion=None

from optparse import OptionParser
parser = OptionParser()
parser.add_option('-d', help='Specify Install Directory.', default=None, dest='installPath')
parser.add_option('-p', help='Specify a version of python you wish to install on for.', default=None, dest='pythVer')
parser.add_option('-u', help='Specify a user you wish to install for.', default='fcadmin', dest='userid')

(options, args) = parser.parse_args()
installPath = options.installPath
if installPath:
	if not os.path.exists(installPath):
		try:os.makedirs(installPath)
		except:
			print "\nCreate install directory failed"
			sys.exit(1)
	installDir = os.path.join(installPath)
	installDirName = os.path.basename(installDir)
	
pythVer = options.pythVer
if pythVer and pythVer == '2.7':
	required_python_ver = (2, 7)
elif pythVer and pythVer == '2.6':
	required_python_ver = (2, 6)
else:
	required_python_ver = None
	
userIdName = options.userid

myDir = os.path.dirname(os.path.realpath(__file__))
os.chdir(myDir)
'''
Parse package version from the (file)name
'''
def getPkgVersion(name):
	vers = '0.0'
	if name:
		token=name.split('fcws-')
		if token:
			ver = token[1].split('.')
			if ver:
				vers = ver[0] + '.' + ver[1] + '.0'
	return vers

'''
Creates a directory in the OS relative to the current working directory.
'''
def createDirectory(path):
	try:
		os.makedirs(path)
	except OSError as exception:
		if exception.errno != errno.EEXIST:
			raise
			
'''
Copies a directory tree from src to dst.
'''
def cpDirectory(src, dst):
	try:
		shutil.copytree(src, dst, symlinks=False, ignore=None)
	except OSError as exception:
			raise
			
'''
Deletes the directory tree at path.
'''			
def removeDirectory(path):
	try:
		shutil.rmtree(path)
	except OSError as exception:
		pass
'''
Remove file/directory for names that start with the prefix pattern          
'''
def remove(path,prefix,verbose=True,singleLevel=True):
	directory = os.listdir(path)
	prefixLen = len(prefix)
	for filename in directory: 
		if filename[:prefixLen].lower() == prefix.lower(): 
			if verbose is not None:
				print >>sys.stderr,  '	Removing: ' + path+pthChar+filename
			if (os.path.isfile(path+pthChar+filename)):
				os.remove(path+pthChar+filename)
			else:
				removeDirectory(path+pthChar+filename)	 
		elif os.path.isdir(path+pthChar+filename):
			if singleLevel:
				continue
			else: 
				remove(path+pthChar+filename,prefix,verbose)

							
def pythonVerDot(ver):
	return str(ver[0]) + '.' + str(ver[1])


def findPackageLocation():
	global mypackagepth
	global PackageLocation
	global libPthList
	global myPackageName
	PackageLocation = None
	mypackagepth = None
	for loc in libPthList:
		if (os.path.exists(loc)):
			for directory in glob.glob(os.path.join(loc,"fcws-*")):
				mypackagepth = directory
				myPackageName = os.path.basename(directory)
				return str(loc)
	
def setPermissions(starting_dir):
	pw = pwd.getpwnam(userIdName)
	uid = pw.pw_uid
	gid = pw.pw_gid
	if (os.path.isfile(starting_dir)):
		try:
			os.chown(starting_dir, uid, gid)
			os.chmod(starting_dir, stat.S_IRWXU | stat.S_IRWXG)
		except:
			pass
	else:
		for root, dirs, files in os.walk(starting_dir):
			try:
				os.chown(os.path.join(starting_dir, root), uid, gid)
				os.chmod(os.path.join(starting_dir, root), stat.S_IRWXU | stat.S_IRWXG)
			except:
				pass
			for f in files:
				if (os.path.isfile(f)):
					try:
						os.chown(os.path.join(starting_dir, root, f), uid, gid)
						os.chmod(os.path.join(starting_dir, root), stat.S_IRWXU | stat.S_IRWXG)
					except:
						pass

def installSetupTools():
	try:
		print "\nInstalling required setuptools package..."
		tempDir = '/usr/local/temp'
		''' Delete tempDir if it exists since cpDirectory creates it '''
		if (os.path.exists(tempDir)):
			removeDirectory(tempDir)
		cpDirectory(os.path.join(myDir,"RequiredPackages","setuptools-0.6c11"),tempDir)
		proc = subprocess.Popen([ pythonpth,"setup.py","install" ], cwd=tempDir, stdout=subprocess.PIPE, stderr=subprocess.PIPE, bufsize=256*1024*1024)
		output, errors = proc.communicate()
		removeDirectory(tempDir)
		if proc.returncode:  
			raise Exception(errors)
		else:
			print output
			return 0
	except Exception as e:
		removeDirectory(tempDir)
		return e

def decompressFile(filePath,targetDir="."):
	print >>sys.stderr,   "Extracting: " + filePath + ' to ' + targetDir
	if os.name == "posix":
		package = tarfile.open(filePath, "r:gz")
	else:
		package = zipfile.ZipFile(filePath, "r")
	package.extractall(targetDir)
	package.close()	
			
#Determine Mac, Linux or Win platform.
if os.name == "posix":
		platformExt='.tar.gz'
		if platform == "osx":
			if required_python_ver is None:
				required_python_ver = (2, 6)
				pythVer = '2.6'
			if not installDir:
				installDir = os.path.join('/Library',installDirName)
			libPthList.append(installDir)	
			startupScriptName = "startfcws.command"
			webserver=os.getenv('FCWS_WebServerConfig', 'cherrypy')
			apacheconf=os.getenv('FCWS_Apache_Conf', '/etc/apache2')
		else:
			if required_python_ver is None:
				required_python_ver = (2, 6)
				pythVer = '2.6'
			if not installDir:
				installDir = os.path.join('/opt',installDirName)
			startupScriptName = "startfcws.sh"
			webserver=os.getenv('FCWS_WebServerConfig', 'cherrypy')
			apacheconf=os.getenv('FCWS_Apache_Conf', '/etc/httpd/conf')
			libPthList.append(installDir)
			libPthList.append('/usr/local/lib/python' + pythonVerDot(required_python_ver) + '/dist-packages')
			libPthList.append('/usr/local/lib64/python' + pythonVerDot(required_python_ver) + '/dist-packages')
			os.environ["PATH"] += os.pathsep + "/usr/local/bin"
			altPths=[]
			for loc in libPthList:
				if loc.find("site-packages") != -1:
					altPths.append(loc.replace("site-packages","dist-packages"))
				elif  loc.find("dist-packages") != -1:
					altPths.append(loc.replace("dist-packages","site-packages"))
			for loc in altPths:
				libPthList.append(loc)
		easyInstallPth='easy_install-' + pythonVerDot(required_python_ver)
else:
		required_python_ver = (2, 7)
		pythVer = '2.7'
		tmp = os.path.splitdrive(pythonpth)[0] + '\\'
		if not installDir:
				installDir = os.path.join(tmp,"Program Files\\",installDirName)
		libPthList.append(installDir)
		easyInstallPth=sys.prefix + '\Scripts\easy_install-' + pythonVerDot(required_python_ver) + '.exe'
		startupScriptName = "startfcws.bat"
		webserver=os.getenv('FCWS_WebServerConfig', 'cherrypy')
		apacheconf=os.getenv('FCWS_Apache_Conf', 'unknown')
		platformExt='.zip'

print "Using easy_install: " + easyInstallPth

if not sys.version_info[:2] == required_python_ver:
	print "Installed python = " + str(sys.version)
	print "Error, This package requires python " + pythonVerDot(required_python_ver)
	sys.exit(2)


 
try:
		import setuptools
except ImportError:
		Install_setupTools=True

if os.name != "posix" and not os.path.exists(easyInstallPth):
		Install_setupTools=True

if Install_setupTools:
	rc = installSetupTools()
	if rc != 0:
		if str(rc).find("/usr/local/lib64/python" + pythonVerDot(required_python_ver) + "/site-packages" ) != -1:
			if not os.path.exists("/usr/local/lib64/python" + pythonVerDot(required_python_ver) + "/site-packages"):
				#Address Install issue on SUSE distro.
				print "\tInstall Error: Creating Directory /usr/local/lib64/python" + pythonVerDot(required_python_ver) + "/site-packages, and trying again."
				createDirectory("/usr/local/lib64/python" + pythonVerDot(required_python_ver) + "/site-packages")
				rc = installSetupTools()
				if rc != 0:
					print "ERROR: Installation of the required setuptools package failed."
					print rc
					sys.exit(3)
		else:	
			print "ERROR: Installation of the required setuptools package failed."
			print rc
			sys.exit(3)


print "\nInstalling required CherryPy package..."
if os.name == "posix":
	proc = subprocess.call( ['sudo',easyInstallPth,'--allow-hosts=None','--find-links=RequiredPackages','CherryPy>3.2.2'] )
else:
	remove(sitePackagesPath,"CherryPy")
	proc = subprocess.call( easyInstallPth + ' --allow-hosts=None -f RequiredPackages "CherryPy>3.2.2"' )

print "\nInstalling required MarkupSafe package..."
if os.name == "posix":
	proc = subprocess.call( ['sudo',easyInstallPth,'--allow-hosts=None','--find-links=RequiredPackages','MarkupSafe>0.14'] )
else:
	remove(sitePackagesPath,"MarkupSafe")
	proc = subprocess.call( easyInstallPth + ' --allow-hosts=None -f RequiredPackages "MarkupSafe>0.14"' )

print "\nInstalling required Mako package..."
if os.name == "posix":
	proc = subprocess.call( ['sudo',easyInstallPth,'--allow-hosts=None','--find-links=RequiredPackages','Mako>0.7.2'] )
else:
	remove(sitePackagesPath,"Mako")
	proc = subprocess.call( easyInstallPth + ' --allow-hosts=None -f RequiredPackages "Mako>0.7.2"' )
	
print "\nInstalling required WebOb package..."
if os.name == "posix":
	proc = subprocess.call( ['sudo',easyInstallPth,'--allow-hosts=None','--find-links=RequiredPackages','WebOb>1.2.3'] )
else:
	remove(sitePackagesPath,"WebOb")
	proc = subprocess.call( easyInstallPth + ' --allow-hosts=None -f RequiredPackages "WebOb>1.2.3"' )

print "\nInstalling required six package..."
if os.name == "posix":
	proc = subprocess.call( ['sudo',easyInstallPth,'--allow-hosts=None','--find-links=RequiredPackages','six>1.1'] )
else:
	remove(sitePackagesPath,"six")
	proc = subprocess.call( easyInstallPth + ' --allow-hosts=None -f RequiredPackages "six>1.1"' )
	
print "\nInstalling required lxml package..."
if os.name == "posix":
	proc = subprocess.call( ['sudo',easyInstallPth,'--allow-hosts=None','--find-links=RequiredPackages','lxml>3.2.2'])
else:
	for file in glob.glob("RequiredPackages\lxml-*"):
				print "\nRunning lxml package installer: " + str(file)
				subprocess.call([file])

print "\nInstall directory: " + installDir

if os.path.exists(os.path.join(installDir,'ConfigBackup')):
	removeDirectory(os.path.join(installDir,'ConfigBackup'))
			
#Check for existing install and back up config files if exists.
PackageLocation = findPackageLocation()
if PackageLocation:
	# Backing up pre-existing config files if present.	
	if glob.glob(mypackagepth):
		#print "\nArchiving existing FirstClass Web Services package: " + str(mypackagepth)
		if not os.path.exists(os.path.join(installDir,archiveDirName)):
			createDirectory(os.path.join(installDir,archiveDirName))
			if os.name == "posix":
				setPermissions(os.path.join(installDir,archiveDirName))
	
	for directory in glob.glob(os.path.join(PackageLocation,"fcws-*")):
		if os.path.isdir(directory):
			pkgArchive = os.path.join(installDir,archiveDirName,ts + '_' + os.path.basename(directory))
			print "\nArchiving existing FirstClass Web Services package: " + str(directory)
			cpDirectory(directory,pkgArchive)
	currentPkgMajorVersion=getPkgVersion(myPackageName)
else:
	print "\nExisting FirstClass Web Services package not found, nothing to backup."


if not os.path.exists(installDir):
	createDirectory(installDir)

if PackageLocation:
	for directory in glob.glob(os.path.join(PackageLocation,"fcws-*")):
		print "\nRemoving pre-existing fcws package: " + str(directory)
		removeDirectory(str(directory))
		
#Find and install included fcws package
for file in glob.glob("fcws-*" + platform + platformExt):
	print "\nInstalling: " + str(file)
	installPackage = file
	if os.name == "posix":
		installPackagePath = myDir + '/' + file
	else:
		installPackagePath = myDir + '\\' + file
	decompressFile(installPackagePath,installDir)
	newPkgMajorVersion=getPkgVersion(file)
	
#Locate newly installed package.
PackageLocation = findPackageLocation()
if PackageLocation:
	print "\nInstalled FirstClass Web Services package located: " + str(mypackagepth)
	if os.name == "posix":
		shutil.copy(mypackagepth + pthChar + "EULA.RTF", installDir + pthChar + "EULA.RTF")
		if platform == "osx":
			if not os.path.exists("/usr/local/fcwsctl"):
				try:
					shutil.copy(mypackagepth + pthChar + "fcwsctl","/usr/local/fcwsctl")	
					os.chmod('/usr/local/fcwsctl', stat.S_IRWXU | stat.S_IRWXG | stat.S_IRWXO)
				except:
					print "\nWARNING: Utility /usr/local/fcwsctl could not be installed."
					shutil.copy(mypackagepth + pthChar + "fcwsctl", installDir + pthChar + "fcwsctl")
			else:
				print "\nUtility /usr/local/fcwsctl exists."
		else:
			if not os.path.exists("/usr/sbin/fcwsctl"):
				try:
					shutil.copy(mypackagepth + pthChar + "fcwsctl","/usr/sbin/fcwsctl")	
					os.chmod('/usr/sbin/fcwsctl', stat.S_IRWXU | stat.S_IRWXG | stat.S_IRWXO)
				except:
					print "\nWARNING: Utility /usr/sbin/fcwsctl could not be installed."
					shutil.copy(mypackagepth + pthChar + "fcwsctl", installDir + pthChar + "fcwsctl")
			else:
				print "\nUtility /usr/sbin/fcwsctl exists."
else:
	print "\nERROR: Could not locate installed FirstClass Web Services package."
	exit(3)

mainPath = "fcws" 

if webserver == "cherrypy":
	print "\nConfiguring installation for the CherryPy web server."
	startupArgs = None
	startupScriptFile = os.path.join(installDir,startupScriptName)
	if os.path.exists(startupScriptFile):
		f = open(startupScriptFile,'r')
		for line in f:
			if 'cherry.pyc' in line:
				tmpstr = re.split('cherry.pyc"', line)
				if len(tmpstr) > 1:
					startupArgs = '"' + tmpstr[1]
				break
		f.close()
		os.remove(startupScriptFile)
	if not os.path.exists(os.path.join(installDir,startupScriptName)):
		print "\t -Creating fcws startup script: " + os.path.join(installDir,startupScriptName)
		if startupArgs is None:
			startupArgs = '" -H 0.0.0.0 -p 80 -e True\n'
		cherrypyStartupStr = os.path.join(mypackagepth,mainPath,"cherry.pyc") + startupArgs
		f = open(os.path.join(installDir,startupScriptName),'w')
		if os.name == "posix":
			f.write('#!/bin/bash\n')
			f.write('sudo ' + pythonpth + ' "' + cherrypyStartupStr)
		else:
			f.write(pythonpth + ' "' + cherrypyStartupStr)
		f.write('\n')
		f.close
else:
	print "\Web server config not supported for: " + webserver

if os.name == "posix":
		print "\nSetting permissions."
		setPermissions(os.path.join(mypackagepth,mainPath,'log'))
		setPermissions(os.path.join(mypackagepth,mainPath,'fcws.cfg'))
		setPermissions(os.path.join(mypackagepth,mainPath,'localized'))
		setPermissions(installDir)
		setPermissions(os.path.join(installDir,startupScriptName))

print "\nDecompressing any version-localized files:"
if os.name == "posix":
	for filePath in  glob.glob(os.path.join(mypackagepth,mainPath,"localized_*.*gz")):
		decompressFile(filePath,os.path.join(mypackagepth,mainPath))
		os.remove(filePath)
else:
	for filePath in  glob.glob(os.path.join(mypackagepth,mainPath,"localized_*.zip")):
		decompressFile(filePath,os.path.join(mypackagepth,mainPath))
		os.remove(filePath)
		
restorepath = mypackagepth		
#Restoring user config & user added icons and html files.
if os.path.exists(os.path.join(installDir,archiveDirName)):
	if pkgArchive:
		''' All sprites from this install package are saved in latest_images directory before '''
		newSpritesPath = os.path.join(restorepath,mainPath,"images","latest_images")
		os.mkdir(newSpritesPath)
		print "\nSaving sprites in images/latest_images before restoring user customizable files:"
		
		for file in glob.glob(os.path.join(restorepath,mainPath,"images","*sprite*.png")):
			print "\t- " + os.path.join(restorepath,mainPath,"images",os.path.basename(file))
			shutil.copy(file, newSpritesPath)
			if os.name == "posix":
				setPermissions(os.path.join(restorepath,mainPath,"images",os.path.basename(file)))	

		print "\nRestoring user customizable files:"
		for file in glob.glob(os.path.join(pkgArchive,mainPath,"fcws.cfg")):
			print "\t- " + os.path.join(restorepath,mainPath,os.path.basename(file))
			shutil.copy(file, os.path.join(restorepath,mainPath))
			if os.name == "posix":
				setPermissions(os.path.join(restorepath,mainPath,os.path.basename(file)))
				
		for file in glob.glob(os.path.join(pkgArchive,mainPath,"css","custom.css")):
			print "\t- " + os.path.join(restorepath,mainPath,os.path.basename(file))
			shutil.copy(file, os.path.join(restorepath,mainPath,"css"))
			if os.name == "posix":
				setPermissions(os.path.join(restorepath,mainPath,"css",os.path.basename(file)))
				
		for file in glob.glob(os.path.join(pkgArchive,mainPath,"images","action_more_ios48_48*.png")):
			print "\t- " + os.path.join(restorepath,mainPath,"images",os.path.basename(file))
			shutil.copy(file, os.path.join(restorepath,mainPath,"images"))
			if os.name == "posix":
				setPermissions(os.path.join(restorepath,mainPath,"images",os.path.basename(file)))
			
		for file in glob.glob(os.path.join(pkgArchive,mainPath,"images","checkbox16_sprite*.png")):
			print "\t- " + os.path.join(restorepath,mainPath,"images",os.path.basename(file))
			shutil.copy(file, os.path.join(restorepath,mainPath,"images"))
			if os.name == "posix":
				setPermissions(os.path.join(restorepath,mainPath,"images",os.path.basename(file)))

		for file in glob.glob(os.path.join(pkgArchive,mainPath,"images","sprite_menu*.png")):
			print "\t- " + os.path.join(restorepath,mainPath,"images",os.path.basename(file))
			shutil.copy(file, os.path.join(restorepath,mainPath,"images"))
			if os.name == "posix":
				setPermissions(os.path.join(restorepath,mainPath,"images",os.path.basename(file)))

		for file in glob.glob(os.path.join(pkgArchive,mainPath,"images","toolbar_icons32_sprite.png")):
			print "\t- " + os.path.join(restorepath,mainPath,"images",os.path.basename(file))
			shutil.copy(file, os.path.join(restorepath,mainPath,"images"))
			if os.name == "posix":
				setPermissions(os.path.join(restorepath,mainPath,"images",os.path.basename(file)))
			
		for file in glob.glob(os.path.join(pkgArchive,mainPath,"images","brand.png")):
			print "\t- " + os.path.join(restorepath,mainPath,"images",os.path.basename(file))
			shutil.copy(file, os.path.join(restorepath,mainPath,"images"))
			if os.name == "posix":
				setPermissions(os.path.join(restorepath,mainPath,"images",os.path.basename(file)))

		for file in glob.glob(os.path.join(pkgArchive,mainPath,"processes.txt")):
			print "\t- " + os.path.join(restorepath,mainPath,os.path.basename(file))
			shutil.copy(file, os.path.join(restorepath,mainPath))
			if os.name == "posix":
				setPermissions(os.path.join(restorepath,mainPath,os.path.basename(file)))
	
		for file in glob.glob(os.path.join(pkgArchive,mainPath,"*.pem")):
			print "\t- " + os.path.join(restorepath,mainPath,os.path.basename(file))
			shutil.copy(file, os.path.join(restorepath,mainPath))
			if os.name == "posix":
				setPermissions(os.path.join(restorepath,mainPath,os.path.basename(file)))

		for file in glob.glob(os.path.join(pkgArchive,mainPath,"images","action_ios","*.png")):
			print "\t- " + os.path.join(restorepath,mainPath,"images","action_ios",os.path.basename(file))
			shutil.copy(file, os.path.join(restorepath,mainPath,"images","action_ios"))
			if os.name == "posix":
				setPermissions(os.path.join(restorepath,mainPath,"images","action_ios",os.path.basename(file)))
		
		print "\t- Any user added files at the root:"
		for rootfile in os.listdir(os.path.join(pkgArchive,mainPath)):
			if os.path.isfile(os.path.join(pkgArchive,mainPath,rootfile)):
				if not os.path.exists(os.path.join(restorepath,mainPath,rootfile)):
					print "\t- " + os.path.join(restorepath,mainPath,rootfile)
					shutil.copy(os.path.join(pkgArchive,mainPath,rootfile),os.path.join(restorepath,mainPath))
		
		print "\t- Any user added icons:"
		for file in os.listdir(os.path.join(pkgArchive,mainPath,"images","icons")):
			if not os.path.exists(os.path.join(restorepath,mainPath,"images","icons",file)):
				print "\t\t-" + file
				shutil.copy(os.path.join(pkgArchive,mainPath,"images","icons",file), os.path.join(restorepath,mainPath,"images","icons"))
				if os.name == "posix":
					setPermissions(os.path.join(restorepath,mainPath,"images","icons",file))
					
		print "\t- Any user added custom images:"
		if os.path.exists(os.path.join(restorepath,mainPath,"images","custom")):
			createDirectory(os.path.join(restorepath,mainPath,"images","custom"))
			for file in os.listdir(os.path.join(pkgArchive,mainPath,"images","custom")):
				print "\t\t-" + file
				shutil.copy(os.path.join(pkgArchive,mainPath,"images","custom",file), os.path.join(restorepath,mainPath,"images","custom"))
				if os.name == "posix":
					setPermissions(os.path.join(restorepath,mainPath,"images","custom",file))
								
		print "\t- Any user added css files:"
		for cssfile in os.listdir(os.path.join(pkgArchive,mainPath,'css')):
			if os.path.isfile(os.path.join(pkgArchive,mainPath,"css",cssfile)):
				if not os.path.exists(os.path.join(restorepath,mainPath,'css',cssfile)):
					print "\t- " + os.path.join(restorepath,mainPath,'css',cssfile)
					shutil.copy(os.path.join(pkgArchive,mainPath,'css',cssfile),os.path.join(restorepath,mainPath,"css"))
					
		print "\t- Any user added css themes files:"
		for theme in os.listdir(os.path.join(pkgArchive,mainPath,'css','themes')):
			if not os.path.isfile(os.path.join(pkgArchive,mainPath,"css",'themes',theme)):
				if not os.path.exists(os.path.join(restorepath,mainPath,'css','themes',theme)):
					print "\t- " + os.path.join(restorepath,mainPath,'css','themes',theme)
					cpDirectory(os.path.join(pkgArchive,mainPath,'css','themes',theme),os.path.join(restorepath,mainPath,"css",'themes',theme))
		
		print "\t- Any user added image files:"
		for image in os.listdir(os.path.join(pkgArchive,mainPath,'images')):
			if os.path.isfile(os.path.join(pkgArchive,mainPath,'images',image)):
				if not os.path.exists(os.path.join(restorepath,mainPath,'images',image)):
					print "\t- " + os.path.join(restorepath,mainPath,'images',image)
					shutil.copy(os.path.join(pkgArchive,mainPath,'images',image),os.path.join(restorepath,mainPath,'images',image))
			else:
				if not os.path.exists(os.path.join(restorepath,mainPath,'images',image)):
					print "\t- " + os.path.join(restorepath,mainPath,'images',image)
					cpDirectory(os.path.join(pkgArchive,mainPath,'images',image),os.path.join(restorepath,mainPath,'images',image))

		print "\t- Any user added localized html files:"
		for file in glob.glob(os.path.join(pkgArchive,mainPath,'localized*')):
			if os.path.isdir(file):
				localizedDirName = os.path.basename(file)
				localizedDestDirName = localizedDirName
				if localizedDirName == 'localized':
					if currentPkgMajorVersion != newPkgMajorVersion:
						''' For major version change copy current "localized" directory user added files
						into new version "localized_X.Y.0" directory '''
						localizedDestDirName = 'localized_' + currentPkgMajorVersion
				if os.path.exists(os.path.join(pkgArchive,mainPath,localizedDirName)):
					if os.path.exists(os.path.join(restorepath,mainPath,localizedDestDirName)):
						for file_name in os.listdir(os.path.join(pkgArchive,mainPath,localizedDirName)):
							if not os.path.isfile(os.path.join(pkgArchive,mainPath,localizedDirName,file_name)):
								if (os.path.exists(os.path.join(pkgArchive,mainPath,localizedDirName,file_name,'user','html','dummy.file'))):
									os.remove(os.path.join(pkgArchive,mainPath,localizedDirName,file_name,'user','html','dummy.file'))
								if (os.path.exists(os.path.join(restorepath,mainPath,localizedDestDirName,file_name,'user','html','dummy.file'))):
									os.remove(os.path.join(restorepath,mainPath,localizedDestDirName,file_name,'user','html','dummy.file'))
								if (os.path.exists(os.path.join(pkgArchive,mainPath,localizedDirName,file_name,'user','html'))):
									if not os.path.exists(os.path.join(restorepath,mainPath,localizedDestDirName,file_name)):
											createDirectory(os.path.join(restorepath,mainPath,localizedDestDirName,file_name))
											if os.name == "posix":
												setPermissions(os.path.join(restorepath,mainPath,localizedDestDirName,file_name))
									if not os.path.exists(os.path.join(restorepath,mainPath,localizedDestDirName,file_name,'user')):
											createDirectory(os.path.join(restorepath,mainPath,localizedDestDirName,file_name,'user'))
											if os.name == "posix":
												setPermissions(os.path.join(restorepath,mainPath,localizedDestDirName,file_name,'user'))
												
									if not os.path.exists(os.path.join(restorepath,mainPath,localizedDestDirName,file_name,'user','html')):
											createDirectory(os.path.join(restorepath,mainPath,localizedDestDirName,file_name,'user','html'))
											if os.name == "posix":
												setPermissions(os.path.join(restorepath,mainPath,localizedDestDirName,file_name,'user','html'))
									for htmlfile in os.listdir(os.path.join(pkgArchive,mainPath,localizedDirName,file_name,'user','html')):
										shutil.copy(os.path.join(pkgArchive,mainPath,localizedDirName,file_name,'user','html',htmlfile),os.path.join(restorepath,mainPath,localizedDestDirName,file_name,'user','html'))
										print "\t- " + os.path.join(restorepath,mainPath,localizedDestDirName,file_name,'user','html',htmlfile)
										if os.name == "posix":
											setPermissions(os.path.join(restorepath,mainPath,localizedDestDirName,file_name,'user','html',htmlfile))
									
									if os.path.exists(os.path.join(pkgArchive,mainPath,localizedDirName,file_name,'user','forms')):		
										if not os.path.exists(os.path.join(restorepath,mainPath,localizedDestDirName,file_name,'user','forms')):
												createDirectory(os.path.join(restorepath,mainPath,localizedDestDirName,file_name,'user','forms'))
												if os.name == "posix":
													setPermissions(os.path.join(restorepath,mainPath,localizedDestDirName,file_name,'user','forms'))
										for htmlfile in os.listdir(os.path.join(pkgArchive,mainPath,localizedDirName,file_name,'user','forms')):
											shutil.copy(os.path.join(pkgArchive,mainPath,localizedDirName,file_name,'user','forms',htmlfile),os.path.join(restorepath,mainPath,localizedDestDirName,file_name,'user','forms'))
											print "\t- " + os.path.join(restorepath,mainPath,localizedDestDirName,file_name,'user','forms',htmlfile)
											if os.name == "posix":
												setPermissions(os.path.join(restorepath,mainPath,localizedDestDirName,file_name,'user','forms',htmlfile))
					else:
						createDirectory(os.path.join(restorepath,mainPath,localizedDestDirName))
						if os.name == "posix":
							setPermissions(os.path.join(restorepath,mainPath,localizedDestDirName))
						cpDirectory(os.path.join(pkgArchive,mainPath,localizedDirName),os.path.join(restorepath,mainPath,localizedDestDirName))
print "\nPerforming cleanup."
# Removing place holder files for empty directories."
for file_name in os.listdir(os.path.join(mypackagepth,mainPath,'localized')):
	if not os.path.isfile(os.path.join(mypackagepth,mainPath,'localized',file_name)):
		if (os.path.exists(os.path.join(mypackagepth,mainPath,'localized',file_name,'user','html','dummy.file'))):
			os.remove(os.path.join(mypackagepth,mainPath,'localized',file_name,'user','html','dummy.file'))
if (os.path.exists(os.path.join(mypackagepth,mainPath,'log','dummy.file'))):
	for file in os.listdir(os.path.join(mypackagepth,mainPath,'log')):
		os.remove(os.path.join(mypackagepth,mainPath,'log',file))

if (os.path.exists(os.path.join(installDir,'RequiredPackages'))):
	removeDirectory(os.path.join(installDir,'RequiredPackages'))
if (os.path.exists(os.path.join(installDir,installPackage))):
	os.remove(os.path.join(installDir,installPackage))
if (os.path.exists(os.path.join(installDir,'install.py'))):
	os.remove(os.path.join(installDir,'install.py'))
		
print "\nInstall complete by " + userIdName

		
