apply plugin: 'io.spring.convention.spring-sample-boot'
apply plugin: "application"

dependencies {
	compile project(':spring-session-data-geode')
	compile "org.springframework.boot:spring-boot-starter-thymeleaf"
	compile "org.springframework.boot:spring-boot-starter-web"
	compile "org.webjars:bootstrap"
	compile "org.webjars:webjars-locator"

	runtime "org.springframework.shell:spring-shell"

	testCompile "org.springframework.boot:spring-boot-starter-test"

	integrationTestCompile seleniumDependencies

	integrationTestRuntime "org.springframework.shell:spring-shell"
}

run {
	doFirst {
		mainClassName = 'sample.server.GemFireServer'
	}
}

bootJar {
	mainClass = 'sample.client.Application'
}

task runGemFireServer() {
	doLast {
		ext.port = reservePort()

		println "Starting GemFire Server on port [$port] ..."

		def out = new StringBuilder()
		def err = new StringBuilder()

		String classpath = sourceSets.main.runtimeClasspath.collect { it }.join(File.pathSeparator)

		String[] commandLine = [
			'java', '-server', '-ea', '-classpath', classpath,
			//"-Dgemfire.log-file=gemfire-server.log",
			//"-Dgemfire.log-level=config",
			"-Dspring-session-data-gemfire.cache.server.port=$port",
			"-Dspring-session-data-gemfire.log.level="
				+ System.getProperty('spring-session-data-gemfire.log.level', 'warning'),
			'sample.server.GemFireServer'
		]

		//println commandLine

		ext.process = commandLine.execute()
		//ext.process = new ProcessBuilder().command(commandLine).redirectErrorStream(true).start();

		ext.process.consumeProcessOutput(out, err)

		//println 'OUT: ' + out
		//println 'ERR: ' + err
	}
}


integrationTest {
	dependsOn runGemFireServer
	doFirst {
		def port = reservePort()
		systemProperties['management.port'] = 0
		systemProperties['server.port'] = port
		//systemProperties['gemfire.log-file'] = "gemfire-client.log"
		//systemProperties['gemfire.log-level'] = "config"
		systemProperties['spring-session-data-gemfire.cache.server.port'] = runGemFireServer.port
		systemProperties['spring-session-data-gemfire.log.level'] = System.getProperty("spring-session-data-gemfire.log.level", "warning")
	}
	doLast {
		println 'Stopping GemFire Server...'
		runGemFireServer.process?.destroyForcibly()
	}
}


def reservePort() {
	def socket = new ServerSocket(0)
	def result = socket.localPort
	socket.close()
	result
}
