#! /usr/bin/env python

import fnmatch
import glob
import os
import subprocess
import shutil
import signal
import sys
import time

# Globals
# The default version of DistMaker
version = '0.41'


def logAndPrint(message="", indent=0, showTime=False):
	while indent > 0:
		indent -= 1
		message = '   ' + message
	if showTime == True:
		message = '[' + getCurrTimeStr() + '] ' + message;
#	logging.info(message)
	print(message)


def buildRelease(version, doNotClean=False):
	# Retrieve the install path
	installPath = getInstallRoot()
	installPath = os.path.dirname(installPath)

	# Check for distMaker.jar library prerequisite
	testPath = os.path.join(installPath, 'lib', 'distMaker.jar')
	if os.path.exists(testPath) == False:
		logAndPrint('Aborting DistMaker release build. The file  ' + testPath + ' does not exist.', indent=1)
		logAndPrint('Please run the buildDistMakerBin.jardesc from your workspace.', indent=1)
		exit(-1)

	# Check for static jre prerequisites
	isPass = os.path.exists(os.path.join(installPath, 'jre'))
	if isPass == False:
		logAndPrint('Aborting DistMaker release build. The jre path is not properly configured.', indent=1)
		logAndPrint('Please setup the jre path properly. A quick fix is to copy the jre tree from a previous release of DistMaker.', indent=1)
		exit(-1)

	# Determine the workPath
	workPath = os.path.join(installPath, 'release', 'DistMaker-' + version)
	destFileGZ = os.path.join(installPath, 'release', 'DistMaker-' + version + '.tar.gz')

	# Bail if the work folder for which we compose the release already exists
	if os.path.exists(workPath) == True:
		logAndPrint('Aborting DistMaker release build. Release folder already exists: ' + workPath, indent=1)
		exit(-1)

	# Bail if the release already exists
	if os.path.exists(destFileGZ) == True:
		logAndPrint('Aborting DistMaker release build. Release already exists. File: ' + destFileGZ, indent=1)
		exit(-1)

	# Laydown the structure, and let the user know of the version we are building
	print('Building DistMaker release ' + version + '...')
	os.mkdir(workPath)

	# Copy the libraries
	dstPath = os.path.join(workPath, 'lib')
	os.mkdir(dstPath)
	for aLib in ['glum.jar', 'guava-18.0.jar', 'distMaker.jar']:
		srcPath = os.path.join(installPath, 'lib', aLib)
		shutil.copy2(srcPath, dstPath)

	# Copy the scripts
	dstPath = os.path.join(workPath, 'script')
	os.mkdir(dstPath)
	for aScript in ['appleUtils.py', 'linuxUtils.py', 'windowsUtils.py', 'buildDist.py', 'deployAppDist.py', 'deployJreDist.py', 'jreUtils.py', 'logUtils.py', 'miscUtils.py']:
		srcPath = os.path.join(installPath, 'script', aScript)
		shutil.copy2(srcPath, dstPath)

	# Copy the (tar.gz) JREs
	globPath = os.path.join(installPath, 'jre/jre-*.tar.gz')
	dstPath = os.path.join(workPath, 'jre')
	os.mkdir(dstPath) 
	for aFile in glob.glob(globPath):
		shutil.copy2(aFile, dstPath)

	# Setup the template tree
	dstPath = os.path.join(workPath, 'template')
	os.makedirs(dstPath + '/apple')
	os.makedirs(dstPath + '/background')
	for aFile in ['appLauncher.jar', '.DS_Store.template', 'apple/JavaAppLauncher', 'apple/JavaApplicationStub', 'background/background.png']:
		srcPath = os.path.join(installPath, 'template', aFile)
		shutil.copy2(srcPath, dstPath + '/' + aFile)

	# Setup the launch4j tree
	l4jPath = os.path.join(installPath, 'template', 'launch4j')
	exeCmd = ['tar', '-C', workPath, '-xf', l4jPath + '/launch4j-3.1.0-beta1-linux.tgz']
	retCode = subprocess.call(exeCmd)
	if retCode != 0:
		print('Failed to extract launch4j package...')
		exit(-1)
	shutil.copy2(l4jPath + '/launch4j', workPath + '/launch4j/')

	# Form the archive
	exeCmd = ['tar', '-czf', destFileGZ, '-C', os.path.dirname(workPath), os.path.basename(workPath)]
	retCode = subprocess.call(exeCmd)
	if retCode != 0:
		print('Failed to build tar.gz file: ' + destFileGZ)
		exit(-1)

	# Remove the workPath
	if doNotClean == False:
		shutil.rmtree(workPath)

	print('DistMaker release ' + version + ' built.')


def getInstallRoot():
	"""Returns the root path where the running script is installed."""
	argv = sys.argv;
	installRoot = os.path.dirname(argv[0])
#	print('appInstallRoot: ' + appInstallRoot)
	return installRoot


def printUsage():
	scriptName = os.path.split(sys.argv[0])[1]
	print(scriptName + ' [-help,-doNotClean,-full],[-version <aVersion>]')
	print('      -help:       Show this help message and exit.')
	print('      -version:    Version to build. Default is: ' + version)
	print('      -doNotClean: Do NOT remove temporary work folder created while generating release.')
	print('      -full:       Force a full build of the main jar file. (Unsupported action)')
	exit(-1)


def handleSignal(signal, frame):
		"""Signal handler, typically used to capture ctrl-c."""
		print('User aborted processing!')
		sys.exit(0)


if __name__ == "__main__":
	argv = sys.argv
	argc = len(argv)

	# Intercept any request for a  help message and bail
	for aArg in argv:
		if aArg == '-h' or aArg == '-help':
			printUsage()
			exit()

	doFullBuild = False
	doNotClean = False
	skipNext = False;
	for currIdx in xrange(1, len(argv)):
		aArg = argv[currIdx]
		if skipNext == True:
			skipNext = False
			continue
		if aArg == '-full':
			doFullBuild = True
		elif aArg == '-doNotClean':
			doNotClean = True
		elif aArg == '-version':
			if currIdx == argc - 1:
				print('\tPlease specify an actual version when using -version')
				exit(-1)
			else:
				version = argv[currIdx + 1]
				skipNext = True
		else:
			print('   Unrecognized argument: ' + aArg)
			printUsage()

	# Logic to capture Ctrl-C and bail
	signal.signal(signal.SIGINT, handleSignal)

	#TODO: Finish this functionality
	if doFullBuild == True:
		print("Unsupported action: [-full]. Skipping...")

	buildRelease(version, doNotClean)
