plugins {
	// osgi
	id "com.diffplug.gradle.osgi.bndmanifest" version "3.4.0"
	// code formatting
	id "com.diffplug.gradle.spotless" version "3.0.0"
	// bintray uploading
	id "com.jfrog.bintray" version "1.3.1"
	// for downloading JRE6
	id "de.undercouch.download" version "2.0.0"
	// github pages
	id "org.ajoberstar.github-pages" version "1.4.2"
}

repositories {
	mavenCentral()
}

//////////
// JAVA //
//////////
apply plugin: 'java'

sourceCompatibility = VER_JAVA
targetCompatibility = VER_JAVA

dependencies {
	testCompile "junit:junit:${VER_JUNIT}"
}

//////////
// OSGI //
//////////
jar.manifest.attributes (
	'Export-Package': 'com.jmatio.*',
	'Import-Package': 'sun.misc;resolution:=optional,com.jmatio.*',
	'Bundle-SymbolicName': "${project.group}.${project.name}",
	'Bundle-Description': "${project.description}",
	'Bundle-Vendor': 'DiffPlug',
	'Bundle-DocURL': "https://github.com/${project.org}/${project.name}",
	'Bundle-License': "https://github.com/${project.org}/${project.name}/blob/v${project.version}/LICENSE",
	'-removeheaders': 'Bnd-LastModified,Bundle-Name,Created-By,Tool',
	'Automatic-Module-Name': 'com.jmatio', // Jigsaw module name
)
// copy the manifest into the WC
osgiBndManifest {
	copyTo 'META-INF/MANIFEST.MF'
}

////////////
// JAVA 6 //
////////////

// matlabcontrol requires at least Java 1.6,
// but older MATLABs run on even older versions

// URL for downloading the JRE6
// others available here, OS doesn't matter: https://github.com/alexkasko/openjdk-unofficial-builds#openjdk-6-build-30
def JDK6_URL = 'https://bitbucket.org/alexkasko/openjdk-unofficial-builds/downloads/openjdk-1.6.0-unofficial-b30-windows-i586-image.zip'
def JDK6_SHA_256 = '8a119a8c9b2ecc48e8457738f57b251e6265b2c0fb232de0ff6fddce0f127045'
// place where the JRE6 will end up
def JDK6_ROOT_DIR = "${buildDir}/jdk"
def JDK6_DST = "${JDK6_ROOT_DIR}/jdk.zip"
def JDK6_DIR = "${JDK6_ROOT_DIR}/unzipped"
def JRE6_HOME = "${JDK6_DIR}/openjdk-1.6.0-unofficial-b30-windows-i586-image/jre"

import de.undercouch.gradle.tasks.download.Download;
import de.undercouch.gradle.tasks.download.Verify;

task downloadJRE6(type: Download) {
	src JDK6_URL
	dest JDK6_DST
	overwrite false
}

task verifyJRE6(dependsOn: downloadJRE6, type: Verify) {
	src downloadJRE6.dest
	algorithm 'SHA-256'
	checksum JDK6_SHA_256
}

task unzipJRE6(dependsOn: verifyJRE6, type: Copy) {
	from zipTree(downloadJRE6.dest)
	into JDK6_DIR
}

// Best bet is to stay at 1.6
sourceCompatibility = 1.6
targetCompatibility = 1.6
def sep = System.getProperty('path.separator')
def bootClasspathStr = "${JRE6_HOME}/lib/rt.jar${sep}${JRE6_HOME}/lib/jsse.jar"
project.tasks.withType(AbstractCompile, { AbstractCompile ac ->
	ac.options.bootClasspath = bootClasspathStr // options is always there but not defined on AbstractCompile so going to hit it anyway
	ac.dependsOn(unzipJRE6)
})

/////////////
// ECLIPSE //
/////////////
apply plugin: 'eclipse'
eclipse {
	project {
		natures 'org.eclipse.pde.PluginNature'
		natures 'org.eclipse.jdt.core.javanature'

		buildCommand 'org.eclipse.jdt.core.javabuilder'
		buildCommand 'org.eclipse.pde.ManifestBuilder'
		buildCommand 'org.eclipse.pde.SchemaBuilder'
	}
	classpath {
		downloadSources true
		downloadJavadoc true
	}
	jdt {
		sourceCompatibility VER_JAVA
		targetCompatibility VER_JAVA
	}
}
// always create fresh projects
tasks.eclipse.dependsOn(cleanEclipse)

////////////
// FORMAT //
////////////
spotless {
	java {
		licenseHeaderFile	'gradle/spotless.license.java'		// License header file
		importOrderFile		'gradle/spotless.importorder'		// An import ordering file, exported from Eclipse
		eclipseFormatFile	'gradle/spotless.eclipseformat.xml'	// XML file dumped out by the Eclipse formatter
		removeUnusedImports()
	}
	format 'misc', {
		target '.gitignore', '*.gradle', '*.md', '.ci/*.sh'
		indentWithTabs()
		trimTrailingWhitespace()
		endWithNewline()
	}
	freshmark {
		target '*.md'
		propertiesFile('gradle.properties')
	}
}

//////////////
// FINDBUGS //
//////////////
apply plugin: 'findbugs'
findbugs {
	toolVersion = VER_FINDBUGS
	sourceSets = [sourceSets.main]	// don't check the test code
	ignoreFailures = false 	// no bugs or it doesn't ship
	reportsDir = file('build/findbugs')
	effort = 'max'			// min|default|max
	reportLevel = 'medium'	// low|medium|high (low = sensitive to even minor mistakes)
	omitVisitors = []		// bugs that we want to ignore
}
// HTML instead of XML
tasks.withType(FindBugs) {
	reports {
		xml.enabled = false
		html.enabled = true
	}
}
// we'll want the findbugs annotations (they don't have a 3.0.1 version)
dependencies {
	compile 'com.google.code.findbugs:annotations:3.0.0'
	compile 'com.google.code.findbugs:jsr305:3.0.0'
}

///////////
// MAVEN //
///////////
apply plugin: 'maven-publish'

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

def verSnapshot = { it.endsWith('-SNAPSHOT') ? 'snapshot' : it }
// Where it's possible to name parameters and methods clearly enough
// that javadoc is not necessary, why make the code bigger?
//
// Thus, no javadoc warnings.
def makeLink = { url, text -> "<a href=\"${url}\" style=\"text-transform: none;\">${text}</a>" }
def javadocInfo = '<h2>' + makeLink("https://github.com/${org}/${name}", "${group}:${name}:${version}") +
' by ' + makeLink('http://www.diffplug.com', 'DiffPlug') + '</h2>'
javadoc {
	options.addStringOption('Xdoclint:none', '-quiet')
	options.header javadocInfo
	options.footer javadocInfo
	options.links('https://docs.oracle.com/javase/6/docs/api/')
}

task javadocJar(type: Jar, dependsOn: javadoc) {
	classifier = 'javadoc'
	from javadoc.destinationDir
}

////////////////
// PUBLISHING //
////////////////
def isSnapshot = project.version.endsWith('-SNAPSHOT')
// pulls the credentials from either the environment variable or gradle.properties
def cred = {
	if (System.env[it] != null) {
		return System.env[it]
	} else if (project.hasProperty(it)) {
		return project[it]
	} else {
		return 'unknown_' + it
	}
}

publishing {
	publications {
		mavenJava(MavenPublication) {
			from components.java
			artifact sourcesJar
			artifact javadocJar
			pom.withXml {
				// findbugs annotations should have scope "provided"
				asNode().dependencies.'*'.findAll() { it.groupId.text() == 'com.google.code.findbugs' }.each() { it.scope*.value = 'provided' }
				// add MavenCentral requirements to the POM
				asNode().children().last() + {
					resolveStrategy = Closure.DELEGATE_FIRST
					name project.name
					description project.description
					url "https://github.com/${project.org}/${project.name}"
					scm {
						url "https://github.com/${project.org}/${project.name}"
						connection "scm:git:git://github.com/${project.org}/${project.name}"
						developerConnection "scm:git:ssh:git@github.com/${project.org}/${project.name}"
					}
					licenses {
						license {
							name 'New BSD License'
							url 'https://github.com/diffplug/matfilerw/blob/v1.3.0/LICENSE'
							distribution 'repo'
						}
					}
					developers {
						developer {
							id 'nedtwigg'
							name 'Ned Twigg'
							email 'ned.twigg@diffplug.com'
						}
					}
				}
			}
		}
	}
	if (isSnapshot) {
		// upload snapshots to oss.sonatype.org
		repositories { maven {
			url = 'https://oss.sonatype.org/content/repositories/snapshots'
			credentials {
				username = cred('nexus_user')
				password = cred('nexus_pass')
			}
		} }
	}
}

if (!isSnapshot) {
	// upload releases to bintray and then mavenCentral
	bintray {
		user = cred('bintray_user')
		key = cred('bintray_pass')
		publications = ['mavenJava']
		publish = true
		pkg {
			repo = 'opensource'
			name = project.name
			userOrg = project.org
			version {
				name = project.version
				mavenCentralSync {
					user = cred('nexus_user')
					password = cred('nexus_pass')
				}
			}
		}
	}

	publish.dependsOn(bintrayUpload)
	bintrayUpload.dependsOn(['generatePomFileForMavenJavaPublication', jar, sourcesJar, javadocJar])
}

//////////////////
// GITHUB PAGES //
//////////////////
githubPages {
	repoUri = "https://github.com/${project.org}/${project.name}"
	deleteExistingFiles = false
	pages {
		from javadoc.destinationDir
		into "javadoc/${verSnapshot(version)}"
	}
	credentials {
		username = cred('gh_token')
		password = ''
	}
}
tasks.prepareGhPages.dependsOn(":javadoc")

// helps external scripts detect version
task printVersion << {
	println version
}
