plugins {
	id 'maven-publish'
	id 'com.gradleup.shadow' version '8.3.9' apply false
	id 'com.diffplug.spotless' version '7.2.1'
}

subprojects {
	apply plugin: 'java'
	apply plugin: 'maven-publish'
	apply plugin: 'checkstyle'
	apply plugin: "com.diffplug.spotless"

	repositories {
		mavenLocal()
		mavenCentral()
		maven { url = 'https://maven.fabricmc.net/' }
	}

	dependencies {
		implementation 'com.google.code.gson:gson:2.10.1'
		implementation 'net.fabricmc:mapping-io:0.7.1'
		
		compileOnly 'org.jetbrains:annotations:24.0.1'

		testImplementation 'junit:junit:4.13.2'
		testImplementation 'org.hamcrest:hamcrest:2.2'
	}

	group = 'cuchaz'
	version = '4.0.0'

	version = version + (System.getenv("GITHUB_ACTIONS") ? "" : "+local")

	java {
		withSourcesJar()
		sourceCompatibility = JavaVersion.VERSION_17
		targetCompatibility = JavaVersion.VERSION_17
	}

	tasks.withType(JavaCompile).configureEach {
		it.options.encoding = "UTF-8"

		it.options.release = 17
	}

	checkstyle {
		configFile = rootProject.file('checkstyle.xml')
		toolVersion = '10.12.4'
	}

	spotless {
		lineEndings = com.diffplug.spotless.LineEnding.UNIX

		java {
			removeUnusedImports()
			importOrder('java', 'javax', '', 'cuchaz.enigma')
		}
	}

	publishing {
		publications {
			"$project.name"(MavenPublication) {
				groupId = project.group
				artifactId = project.name
				version = project.version
				from components.java
			}
		}
	}
}

allprojects {
	publishing {
		repositories {
			mavenLocal()

			def ENV = System.getenv()
			if (ENV.MAVEN_URL) {
				maven {
					url ENV.MAVEN_URL
					credentials {
						username ENV.MAVEN_USERNAME
						password ENV.MAVEN_PASSWORD
					}
				}
			}
		}
	}
}

// A task to ensure that the version being released has not already been released.
tasks.register('checkVersion') {
	doFirst {
		def xml = new URL("https://maven.fabricmc.net/cuchaz/enigma/maven-metadata.xml").text
		def metadata = new groovy.xml.XmlSlurper().parseText(xml)
		def versions = metadata.versioning.versions.version*.text();
		if (versions.contains(version)) {
			throw new RuntimeException("${version} has already been released!")
		}
	}
}

publish.mustRunAfter checkVersion
