apply plugin: 'war'
apply plugin: 'tomcat'
apply plugin: 'artifactory'
apply plugin: 'maven'


sourceCompatibility = 1.7
group = 'com.tooltwist'
version = '0.1'

def TOOLTWIST_VERSION = '{{TOOLTWIST_VERSION}}';
def TOMCAT_VERSION = '7.0.42'

httpPort = {{&HTTP_PORT}}
//httpsPort = {{&HTTPS_PORT}}
//ajpPort = {{&AJP_PORT}}

buildscript {
    repositories {
        maven { url 'http://jcenter.bintray.com' }
    }
    dependencies {
        classpath(group: 'org.jfrog.buildinfo', name: 'build-info-extractor-gradle', version: '2.0.9')
        classpath 'org.gradle.api.plugins:gradle-tomcat-plugin:0.9.8'
    }
}
/*
buildscript {
	repositories {
		maven {
			url {{&RESOLVE_CONTEXTURL}} + {{&RESOLVE_REPO}}
			credentials {
				username = {{&REPO_USER}}
				password = {{&REPO_PASSWORD}}
			}
		}
		mavenCentral()
	}

    dependencies {
        classpath 'org.gradle.api.plugins:gradle-tomcat-plugin:0.9.8'
    }
}
*/

artifactory {
        resolve {
                repository {
                    contextUrl = {{&RESOLVE_CONTEXTURL}}
                    repoKey = {{&RESOLVE_REPO}}
                    username = {{&REPO_USER}}
                    password = {{&REPO_PASSWORD}}
                    maven = true
                }
        }
}
/*
repositories {
	maven {
		url {{&RESOLVE_CONTEXTURL}} + {{&RESOLVE_REPO}}
			credentials {
			username = {{&REPO_USER}}
			password = {{&REPO_PASSWORD}}
		}
	}
}
*/

configurations {
	zipConfiguration
}

// Reload snapshot dependencies (POM) if updated
// http://stackoverflow.com/questions/13565082/how-can-i-force-gradle-to-redownload-dependencies
configurations.all {
    // check for updates every build
    resolutionStrategy.cacheChangingModulesFor 0, 'seconds'
}


dependencies {

	// Tomcat dependencies
	// See https://github.com/bmuschko/gradle-tomcat-plugin
	tomcat "org.apache.tomcat.embed:tomcat-embed-core:${TOMCAT_VERSION}", "org.apache.tomcat.embed:tomcat-embed-logging-juli:${TOMCAT_VERSION}"

	tomcat("org.apache.tomcat.embed:tomcat-embed-jasper:${TOMCAT_VERSION}") {
		exclude group: 'org.eclipse.jdt.core.compiler', module: 'ecj'
	}

	// Application dependencies
	{{#projects}}
	compile group: '{{&group}}', name: '{{&name}}', version: '{{&version}}', transitive: true, changing: true
	zipConfiguration '{{&group}}:{{&name}}:{{&version}}:tooltwist-config@zip'
	zipConfiguration '{{&group}}:{{&name}}:{{&version}}:tooltwist-widgets@zip'
	zipConfiguration '{{&group}}:{{&name}}:{{&version}}:tooltwist-webcontent@zip'
	//zipConfiguration '{{&group}}:{{&name}}:{{&version}}:sources@jar'

	{{/projects}}

	// Provide a security plugin
	compile group: 'com.tooltwist', name: 'ttsec-standaloneDesigner', version: TOOLTWIST_VERSION, transitive: true, changing: true
	zipConfiguration "com.tooltwist:ttsec-standaloneDesigner:${TOOLTWIST_VERSION}:tooltwist-config@zip"
	zipConfiguration "com.tooltwist:ttsec-standaloneDesigner:${TOOLTWIST_VERSION}:tooltwist-widgets@zip"
	zipConfiguration "com.tooltwist:ttsec-standaloneDesigner:${TOOLTWIST_VERSION}:tooltwist-webcontent@zip"

	// This might be just temporary
	compile 'mysql:mysql-connector-java:5.1.24'

	testCompile group: 'junit', name: 'junit', version: '4.+'
}


task expandZipFiles << {

	// Check the repos for the ZIP dependencies, allowing leniency for those that do not exist.
	def artifacts = configurations.zipConfiguration.getResolvedConfiguration().getLenientConfiguration().getArtifacts(Specs.SATISFIES_ALL)

	// Extract the content from the zip files.
	artifacts.each {
		//println "\nArtifact=" + it.inspect()
		//println "type=" + it.classifier
		//println "file=" + it.file

		def projectname = it.name
		def zipfile = it.file
		
		def timestampFile = new File('timestamp-' + zipfile.name)
		if (timestampFile.exists() && timestampFile.lastModified() >= zipfile.lastModified()) {
			
			// Already extracted the files.
			logger.info("  - already expanded ${zipfile.name}")
		} else {
			
			// Not already expanded, extract the files now
			logger.info("  - expanding ${zipfile.name}")

			def dest
			switch (it.classifier) {
			case 'tooltwist-config': dest = "../../extension-projects/${projectname}/config"; break;
			case 'tooltwist-widgets': dest = "../../extension-projects/${projectname}/widgets"; break;
			case 'tooltwist-webcontent': dest = "src/main/webapp"; break;
			}
			if (dest) {
				copy {
					from zipTree(zipfile)
					//into "../../extension-projects/${projectName}/config"
					//into "src/main/webapp"
					into dest
					includeEmptyDirs = true
				}
			}
			
			// Update the timestamp file
			timestampFile.createNewFile()
		}
		
		
	}

return

	{{#projects}}
	extractFromJar('{{&group}}', '{{&name}}', '{{&version}}')
	{{/projects}}
	
	// Don't forget the security plugin
	extractFromJar('com.tooltwist', 'ttsec-standaloneDesigner', TOOLTWIST_VERSION)
	println( )
}

task designer << {

}
designer.dependsOn('tomcatRun')



task explodedWar << {
	File explodedDir = "$buildDir/../exploded" as File
	ant.unzip(src: war.archivePath, dest: explodedDir)
}
explodedWar.dependsOn('war')
war.dependsOn('expandZipFiles')
tomcatRun.dependsOn('expandZipFiles')

def extractFromJar(group, projectName, version) {

	println '--> ' + group + ', ' + projectName + ', ' + version

	// Find the jar file for this project
	// It'll have a name something like this...'
	// /Users/philipcallender/.gradle/caches/modules-2/files-2.1/com.tooltwist/tooltwist/8.3.1.1/f9c...973/tooltwist-8.3.1.1.jar
	
	// Match against a string like this: "/com.tooltwist/tooltwist/"
	def pattern = '/' + group + '/' + projectName + '/'
	//println '  pattern: ' + pattern
	def jars = project.configurations.runtime.filter {
		
		//println '  ? ' + it.name + ', ' + it.path
		def path = it.path
		if (path.indexOf(pattern) >= 0 && path.endsWith('.jar')) {
			//println '    MATCH'
			return true;
		}
		return false;
	}
	

	// Pull the tooltwist files out of the jar
	jars.each { jarFile ->
		println '    extracting from ' + jarFile

		// Find config and widget files
		// Copy files into tooltwist/extension-projects/<project-name>/{config | widget}
		FileTree zip = zipTree(jarFile).matching {
		    include 'META-INF/tooltwist/config/**'
		    include 'META-INF/tooltwist/widgets/**'
		}
		copy {
			from zip
			into '../../extension-projects/'
			eachFile {details ->
				details.path = details.path.replaceAll("META-INF/tooltwist/", projectName + "/")
		    }
			includeEmptyDirs = false
		}

		// Find resource files (web assets)
		// Copy files into tooltwist/extension-projects/<project-name>/WebContent
		zip = zipTree(jarFile).matching {
		    include 'META-INF/resources/**'
		}
		copy {
			from zip
			into '../../extension-projects/'
			eachFile {details ->
				details.path = details.path.replaceAll("META-INF/resources/", projectName + "/WebContent/")
		    }
			includeEmptyDirs = false
		}
	}
}




//----------------------------------------------
// Tasks related to generating
// See https://github.com/bmuschko/gradle-tomcat-plugin
ext {
    tomcatStopPort = {{&STOP_PORT}}
    tomcatStopKey = 'stopKey'
}

tomcatRun {
	httpPort = {{&HTTP_PORT}}
//	httpsPort = {{&HTTPS_PORT}}
//	ajpPort = {{&AJP_PORT}}
}

task generateTomcatRun(type: org.gradle.api.plugins.tomcat.TomcatRun) {
	stopPort = tomcatStopPort
	stopKey = tomcatStopKey
	daemon = true
}
generateTomcatRun.dependsOn('expandZipFiles')

task generateTomcatStop(type: org.gradle.api.plugins.tomcat.TomcatStop) {
    stopPort = tomcatStopPort
    stopKey = tomcatStopKey
}

task phase2 << {
	//println("****** GENERATE FILES - start")
	println("***************************************************************************");
	println("***                                                                     ***");
	println("***              PHASE 2 - (generate, grunt, install, etc)              ***");
	println("***                                                                     ***");
	println("***************************************************************************");		
	
	// See http://www.joergm.com/2010/09/executing-shell-commands-in-groovy/

	/*
	// Check all the Node packages are loaded
	println('$ cd {{&HIDDEN_DIR}}/PHASE2')
	println('$ npm install --quiet')
	def process = new ProcessBuilder( ['npm', '--quiet', 'install'] )
	                .directory(new File('{{&HIDDEN_DIR}}/PHASE2'))
	                .redirectErrorStream(true) // merge stdin and stdout
	                .start()
	process.inputStream.eachLine {println it}
	process.waitFor()
	if (process.exitValue() != 0) {
		// throw new GradleException("Package updating failed");
		// This is frowned upon, but grunt will have already given an error message.
		System.exit(1);
	}
	*/

	// Run grunt
	println('$ cd {{&HIDDEN_DIR}}/PHASE2')
	println('$ ./DOIT')
	def process2 = new ProcessBuilder("./DOIT")
                    .directory(new File('{{&HIDDEN_DIR}}/PHASE2'))
                    .redirectErrorStream(true) // merge stdin and stdout
                    .start()
	process2.inputStream.eachLine {println it}
	process2.waitFor()
	if (process2.exitValue() != 0) {
		// throw new GradleException("Grunt execution failed");
		// This is frowned upon, but grunt will have already given an error message.
		System.exit(1);
	}
}
phase2.dependsOn('generateTomcatRun')
phase2.finalizedBy('generateTomcatStop')




//----------------------------------------------
// Prepare all the files required to install
//	- build and start server
//	- extract config and widget files
//	- generate files
//	- stop server
//
task run_tomcat_and_phase2 << {
}
run_tomcat_and_phase2.dependsOn('war')
run_tomcat_and_phase2.dependsOn('explodedWar')
run_tomcat_and_phase2.dependsOn('phase2')
{{#USE_PHASE2}}
{{/USE_PHASE2}}
