plugins {
	id 'java-library'
	id 'maven-publish'
	id 'signing'
	id 'jacoco'
	id "com.diffplug.spotless" version "7.2.1"
}

allprojects {
	repositories {
		mavenCentral()
	}
}

project.group = "com.microsoft.onnxruntime"
// cmake runs will inform us of the build directory of the current run
def cmakeBuildDir = System.properties['cmakeBuildDir']
def useCUDA = System.properties['USE_CUDA']

boolean enableTrainingApis = (System.properties['ENABLE_TRAINING_APIS'] ?: "0") == "1"
def cmakeJavaDir = "${cmakeBuildDir}/java"
def cmakeNativeLibDir = "${cmakeJavaDir}/native-lib"
def cmakeNativeJniDir = "${cmakeJavaDir}/native-jni"
def cmakeNativeTestDir = "${cmakeJavaDir}/native-test"
def cmakeBuildOutputDir = "${cmakeJavaDir}/build"

def tmpArtifactId = enableTrainingApis ? project.name + "-training" : project.name
def mavenArtifactId = (useCUDA == null) ? tmpArtifactId : tmpArtifactId + "_gpu"

def defaultDescription = 'ONNX Runtime is a performance-focused inference engine for ONNX (Open Neural Network Exchange) models.'
def trainingDescription = 'ONNX Runtime Training is a training and inference package for ONNX ' +
	'(Open Neural Network Exchange) models. This package is targeted for Learning on The Edge aka On-Device Training ' +
	'See https://github.com/microsoft/onnxruntime-training-examples/tree/master/on_device_training for more details.'


java {
	sourceCompatibility = JavaVersion.VERSION_17
	targetCompatibility = JavaVersion.VERSION_17
}

// This jar tasks serves as a CMAKE signaling
// mechanism. The jar will be overwritten by allJar task
jar {
}

// Add explicit sources jar with pom file.
tasks.register('sourcesJar', Jar) {
	dependsOn classes
	archiveClassifier = "sources"
	from sourceSets.main.allSource
	into("META-INF/maven/$project.group/$mavenArtifactId") {
		from { generatePomFileForMavenPublication }
		rename ".*", "pom.xml"
	}
}

// Add explicit javadoc jar with pom file
tasks.register('javadocJar', Jar) {
	dependsOn javadoc
	archiveClassifier = "javadoc"
	from javadoc.destinationDir
	into("META-INF/maven/$project.group/$mavenArtifactId") {
		from { generatePomFileForMavenPublication }
		rename ".*", "pom.xml"
	}
}

spotless {
	java {
		removeUnusedImports()
		googleJavaFormat()
		targetExclude "src/test/java/ai/onnxruntime/OnnxMl.java"
	}
	format 'gradle', {
		target '**/*.gradle'
		trimTrailingWhitespace()
		indentWithTabs()
	}
}

compileJava {
	dependsOn spotlessJava
	options.compilerArgs += ["-h", "${layout.buildDirectory.get().toString()}/headers/"]
	if (!JavaVersion.current().isJava8()) {
		// Ensures only methods present in Java 8 are used
		options.compilerArgs.addAll(['--release', '8'])
		// Gradle versions before 6.6 require that these flags are unset when using "-release"
		java.sourceCompatibility = null
		java.targetCompatibility = null
	}
}

compileTestJava {
	if (!JavaVersion.current().isJava8()) {
		// Ensures only methods present in Java 8 are used
		options.compilerArgs.addAll(['--release', '8'])
		// Gradle versions before 6.6 require that these flags are unset when using "-release"
		java.sourceCompatibility = null
		java.targetCompatibility = null
	}
}

sourceSets.main.java {
	srcDirs = ['src/main/java', 'src/main/jvm']
}

sourceSets.test {
	// add test resource files
	resources.srcDirs += [
		"${rootProject.projectDir}/../csharp/testdata",
		"${rootProject.projectDir}/../onnxruntime/test/testdata",
		"${rootProject.projectDir}/../onnxruntime/test/testdata/training_api",
		"${rootProject.projectDir}/../java/testdata"
	]
	if (cmakeBuildDir != null) {
		// add compiled native libs
		resources.srcDirs += [
			cmakeNativeLibDir,
			cmakeNativeJniDir,
			cmakeNativeTestDir
		]
	}
}

if (cmakeBuildDir != null) {
	// generate tasks to be called from cmake

	// Overwrite jar location
	tasks.register('allJar', Jar) {
		manifest {
			attributes('Automatic-Module-Name': project.group,
					'Implementation-Title': 'onnxruntime',
					'Implementation-Version': project.version)
		}
		into("META-INF/maven/$project.group/$mavenArtifactId") {
			from { generatePomFileForMavenPublication }
			rename ".*", "pom.xml"
		}
		from sourceSets.main.output
		from cmakeNativeJniDir
		from cmakeNativeLibDir
	}

	tasks.register('cmakeBuild', Copy) {
		from layout.buildDirectory.get()
		include 'libs/**'
		include 'docs/**'
		into cmakeBuildOutputDir
		dependsOn(allJar, sourcesJar, javadocJar, javadoc)
	}

	tasks.register('cmakeCheck', Copy) {
		group = 'verification'
		from layout.buildDirectory.get()
		include 'reports/**'
		into cmakeBuildOutputDir
		dependsOn(check)
	}
} else {
	println "cmakeBuildDir is not set. Skipping cmake tasks."
}

dependencies {
	testImplementation 'org.junit.jupiter:junit-jupiter-api:5.9.2'
	testRuntimeOnly 'org.junit.jupiter:junit-jupiter-engine:5.9.2'
	testImplementation 'com.google.protobuf:protobuf-java:4.33.6'
}

processTestResources {
	duplicatesStrategy(DuplicatesStrategy.INCLUDE) // allows duplicates in the test resources
}

test {
	java {
		dependsOn spotlessJava
	}
	if (System.getProperty("JAVA_FULL_TEST") != null) {
		// Forces each test class to be run in a separate JVM,
		// which is necessary for testing the environment thread pool which is ignored if full test is not set.
		forkEvery 1
	}
	useJUnitPlatform()
	if (cmakeBuildDir != null) {
		workingDir cmakeBuildDir
	}
	systemProperties System.getProperties().subMap([
		'ENABLE_TRAINING_APIS',
		'JAVA_FULL_TEST',
		'USE_ACL',
		'USE_AZURE',
		'USE_CANN',
		'USE_COREML',
		'USE_CUDA',
		'USE_DML',
		'USE_DNNL',
		'USE_MIGRAPHX',
		'USE_NNAPI',
		'USE_NV',
		'USE_OPENVINO',
		'USE_QNN',
		'USE_RKNPU',
		'USE_SNPE',
		'USE_TENSORRT',
		'USE_VITISAI',
		'USE_VSINPU',
		'USE_WEBGPU',
		'USE_WEBNN',
		'USE_XNNPACK',
		])
	testLogging {
		events "passed", "skipped", "failed"
		showStandardStreams = true
		showStackTraces = true
		exceptionFormat = "full"
	}
}

jacocoTestReport {
	reports {
		xml.required = true
		csv.required = true
		html.outputLocation = layout.buildDirectory.dir("jacocoHtml")
	}
}

publishing {
	publications {
		maven(MavenPublication) {
			groupId = project.group
			artifactId = mavenArtifactId
			from components.java

			version = project.version
			pom {
				name = enableTrainingApis ? 'onnxruntime-training' : 'onnx-runtime'
				description = enableTrainingApis ? trainingDescription : defaultDescription
				url = 'https://microsoft.github.io/onnxruntime/'
				licenses {
					license {
						name = 'MIT License'
						url = 'https://opensource.org/licenses/MIT'
					}
				}
				organization {
					name = 'Microsoft'
					url = 'https://www.microsoft.com'
				}
				scm {
					connection = 'scm:git:git://github.com:microsoft/onnxruntime.git'
					developerConnection = 'scm:git:ssh://github.com/microsoft/onnxruntime.git'
					url = 'https://github.com/microsoft/onnxruntime'
				}
				developers {
					developer {
						id = 'onnxruntime'
						name = 'ONNX Runtime'
						email = 'onnxruntime@microsoft.com'
					}
				}
			}
		}
	}
}
// Generates a task signMavenPublication that will
// build all artifacts.
signing {
	// Queries env vars:
	// ORG_GRADLE_PROJECT_signingKey
	// ORG_GRADLE_PROJECT_signingPassword but can be changed to properties
	def signingKey = findProperty("signingKey")
	def signingPassword = findProperty("signingPassword")
	// Skip signing if no key is provided
	if (signingKey != null && signingPassword != null) {
		useInMemoryPgpKeys(signingKey, signingPassword)
		sign publishing.publications.maven
	}
}

tasks.named('generatePomFileForMavenPublication') {
	doFirst {
		println "AGENT_LOG: Generating POM for version: ${project.version}"
	}
}
