import java.nio.charset.Charset

// http://jedicoder.blogspot.com.es/2011/11/automated-gradle-project-deployment-to.html
buildscript {
	repositories {
		mavenLocal()
		mavenCentral()
		jcenter()
	}

	dependencies {
		// Kotlin JVM
		classpath "org.jetbrains.kotlin:kotlin-gradle-plugin:$kotlinVersion"
	}
}

plugins {
	// Bintray
	id "com.jfrog.bintray" version "$bintrayVersion"
}

apply plugin: 'idea'

//tasks.withType(Test) {
//	scanForTestClasses = false
//	include "**/*Test.class" // whatever Ant pattern matches your test class files
//}

allprojects { project ->
	//task hello << {task ->
	//	println "I'm $task.project.name: ${task.project.ext.jtranscVersion}"
	//}
	ext {
		// Kotlin JVM
		general_kotlinVersion = kotlinVersion

		// Junit
		junitVersion = "4.12"

		project.ext.kotlinVersion = kotlinVersion
		project.ext.jtranscVersion = "${jtranscVersion}"
	}

	repositories {
		jcenter()
	}

	apply plugin: 'java'
	apply plugin: 'maven'
	apply plugin: 'maven-publish'
	apply plugin: 'signing'

	apply plugin: 'com.jfrog.bintray'

	project.version = jtranscVersion

	// Java target version
	sourceCompatibility = 1.8
	targetCompatibility = 1.8

	//apply from: '../include.gradle'

	dependencies {
		// Junit
		testImplementation "junit:junit:$junitVersion"
	}

	test {
		minHeapSize = "128m"
		maxHeapSize = "2g"
	}
}

def sed = { String file, /* language=RegExp */ String regexp, String replacement ->
	def f = new File(file)
	if (f.exists()) {
		def content = f.getText("UTF-8")
		def res = content.replaceAll(regexp, replacement)
		//println(res)
		f.write(res)
	}
}

println("Charset.defaultCharset(): " + Charset.defaultCharset())

task updateVersion() {
	doLast {
		def newversion = jtranscVersion
		println "Updating jtransc to version '$newversion'"
		println "Updating kotlin to version '$kotlinVersion'"

		def isSnapshot = "$newversion".endsWith("-SNAPSHOT")

		// JTransc version
		sed("jtransc-rt-core/src/com/jtransc/JTranscVersion.java", 'static private final String version = "(.*)"', "static private final String version = \"$newversion\"")
		sed("gradle.properties", 'jtranscVersion=(.*)', "jtranscVersion=$newversion")
		sed("jtransc-main-run/example-gradle/gradle.properties", 'jtranscVersion=(.*)', "jtranscVersion=$newversion")
		sed("jtransc-main-run/example-gradle-multi/gradle.properties", 'jtranscVersion=(.*)', "jtranscVersion=$newversion")
		sed("benchmark/gradle.properties", 'jtranscVersion=(.*)', "jtranscVersion=$newversion")
		sed("jtransc-maven-plugin/resources/META-INF/maven/com.jtransc/jtransc-maven-plugin/pom.properties", 'version=(.*)', "version=$newversion")
		sed("jtransc-main-run/pom.xml", '<!--jtransc--><version>(.*)<\\/version>', "<!--jtransc--><version>$newversion</version>")
		sed("jtransc-maven-plugin/example/pom.xml", '<!--jtransc--><version>(.*)<\\/version>', "<!--jtransc--><version>$newversion</version>")
		sed("jtransc-maven-plugin/resources/META-INF/maven/com.jtransc/jtransc-maven-plugin/plugin-help.xml", '<!--jtransc--><version>(.*)<\\/version>', "<!--jtransc--><version>$newversion</version>")
		sed("jtransc-maven-plugin/resources/META-INF/maven/com.jtransc/jtransc-maven-plugin/pom.xml", '<!--jtransc--><version>(.*)<\\/version>', "<!--jtransc--><version>$newversion</version>")
		sed("jtransc-maven-plugin/resources/META-INF/maven/plugin.xml", '<!--jtransc--><version>(.*)<\\/version>', "<!--jtransc--><version>$newversion</version>")

		// JTransc non-snapshot versions
		if (!isSnapshot) {
			sed("README.md", 'id "com.jtransc" version "(.*)"', "id \"com.jtransc\" version \"$newversion\"")
		}

		// Kotlin version
		sed("jtransc-utils/src/com/jtransc/KotlinVersion.kt", 'val KotlinVersion = "(.*)"', "val KotlinVersion = \"$kotlinVersion\"")
		sed("jtransc-maven-plugin/resources/META-INF/maven/plugin.xml", '<!--kotlin--><version>(.*)<\\/version>', "<!--kotlin--><version>$kotlinVersion</version>")
		sed("jtransc-maven-plugin/example/pom.xml", '<!--kotlin--><version>(.*)<\\/version>', "<!--kotlin--><version>$kotlinVersion</version>")
	}
}

task travisDeploy(dependsOn: ['bintrayUpload']) {
	doLast {
		println("Deployed!")
	}
}

task snapshotTask() {
}

task releaseTask() {
}

if ("$jtranscVersion".endsWith("-snapshot")) {
	travisDeploy.dependsOn('snapshotTask')
} else {
	travisDeploy.dependsOn('releaseTask')
}

clean.doFirst {
	delete "${project.rootDir}/classes"
	for (p in project.allprojects) {
		delete "${p.projectDir}/out"
		println "Deleting... ${p.projectDir}/out"
	}
}

idea {
	module {
		excludeDirs = [
			file(".gradle"), file(".idea"), file(".github"), file("build"),
			file("docs"), file("benchmark"), file("benchmark_kotlin_mpp"),
			file("examples"), file("extra"),
			file("gradle"), file("inception"),
			file("jtransc-intellij-plugin"), file("jtransc-main-run")
		]
	}
}

subprojects {
	def hasKotlin = project.name != "jtransc-annotations" && project.name != "jtransc-rt" && project.name != "jtransc-rt-core"

	apply plugin: 'maven-publish'
	apply plugin: 'com.jfrog.bintray'
	apply plugin: 'jacoco'

	def props = rootProject.extensions.getExtraProperties()

	//if (!props.has("gitVersion")) {
	//	try {
	//		props.set("gitVersion", "git describe".execute().text.trim())
	//	} catch (Throwable) {
	//		props.set("gitVersion", "${jtranscVersion}")
	//	}
	//}

	//def publicationVersion = ("$project.version".endsWith("-SNAPSHOT") ? (props.get("gitVersion") ?: "$project.version") ?: "$project.version" ?: "unknown"
	def publicationVersion = project.version

	publishing {
		publications {
			MyPublication(MavenPublication) {
				from components.java
				groupId group
				artifactId project.name
				version publicationVersion
			}
		}
	}

	bintray {
		user = System.getenv("BINTRAY_USER") ?: properties['BINTRAY_USER'] ?: rootProject.properties['BINTRAY_USER']
		key = System.getenv("BINTRAY_KEY") ?: properties['BINTRAY_USER'] ?: rootProject.properties['BINTRAY_KEY']

		publications = ['MyPublication']

		dryRun = false
		publish = true
		if ("$project.version".endsWith("-SNAPSHOT")) {
			override = true
		}

		pkg {
			userOrg = 'jtransc'
			repo = 'jtransc'
			name = 'jtransc'
			//name = rootProject.name
			licenses = ['Apache-2.0']
			vcsUrl = 'https://github.com/jtransc/jtransc.git'
		}
	}

	jacocoTestReport {
		reports {
			xml.enabled true
			html.enabled false
			csv.enabled false
		}
	}

	check.dependsOn jacocoTestReport

	group = group
	version = "${project.ext.jtranscVersion}"

	compileJava.options.encoding = 'UTF-8'
	compileTestJava.options.encoding = 'UTF-8'

	configurations {
		provided
	}
	sourceSets {
		main { compileClasspath += configurations.provided }
	}

	repositories {
		mavenLocal()
		mavenCentral()
	}

	if (hasKotlin) {
		apply plugin: 'kotlin'

		// https://kotlinlang.org/docs/reference/using-gradle.html#compiler-options

		compileKotlin {
			kotlinOptions.suppressWarnings = true
		}
		compileTestKotlin {
			kotlinOptions.suppressWarnings = true
		}
		dependencies {
			// Kotlin
			implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk8:${kotlinVersion}"
			implementation "org.jetbrains.kotlin:kotlin-reflect:${kotlinVersion}"
		}
	}

	sourceSets {
		main.java.srcDirs = [ 'src' ]
		main.resources.srcDirs = [ 'resources' ]
		test.java.srcDirs = [ 'test' ]
		test.resources.srcDirs = [ 'testresources' ]
		if (hasKotlin) {
			main.kotlin.srcDirs = ['src']
			test.kotlin.srcDirs = ['test']
		}
	}

	if (System.getenv("JTRANCS_DEPLOY") != null) {
		task javadoc2(type: Javadoc) {
			failOnError = false
		}

		task javadocJar(type: Jar, dependsOn: javadoc2) {
			classifier = 'javadoc'
			from 'build/docs/javadoc'
		}

		task sourcesJar(type: Jar) {
			from sourceSets.main.allSource
			classifier = 'sources'
		}

		artifacts {
			archives jar
			archives javadocJar
			archives sourcesJar
		}

		signing {
			sign configurations.archives
		}

		uploadArchives {
			repositories {
				mavenDeployer {
					beforeDeployment { MavenDeployment deployment -> signing.signPom(deployment) }

					repository(url: "https://oss.sonatype.org/service/local/staging/deploy/maven2/") {
						authentication(userName: sonatypeUsername, password: sonatypePassword)
					}

					pom.project {
						name "${project.name}"
						packaging 'jar'
						description 'JVM AOT compiler currently generating JavaScript, C++, C# and Dart, with initial focus on Kotlin and games.'
						url 'https://github.com/jtransc/jtransc/'
						inceptionYear '2015'

						scm {
							url 'scm:git@github.com:jtransc/jtransc.git'
							connection 'scm:git@github.com:jtransc/jtransc.git'
							developerConnection 'scm:git@github.com:jtransc/jtransc.git'
						}

						licenses {
							license {
								name 'The Apache Software License, Version 2.0'
								url 'http://www.apache.org/licenses/LICENSE-2.0.txt'
								distribution 'repo'
							}
						}

						developers {
							developer {
								id 'soywiz'
								name 'Carlos Ballesteros Velasco'
							}
						}
					}
				}
			}
		}
	}
}