import io.github.fabricators_of_create.porting_lib_build.tasks.FmjExpander
import io.github.fabricators_of_create.porting_lib_build.PortingLibBuildPlugin

plugins {
	id "fabric-loom"
	id "maven-publish"
}

sourceCompatibility = JavaVersion.VERSION_17
targetCompatibility = JavaVersion.VERSION_17

archivesBaseName = "porting_lib"

Provider<String> branchProvider = providers.exec {
	it.setCommandLine("git", "branch", "--show-current")
}.standardOutput.asText.map {
	it.contains("not a git repository") ? "unknown" : it.trim()
}

String versionNumber = providers.provider {
	String version = mod_version // 2.3.1
	if (System.getenv("SNAPSHOT") == "true") {
		version += "-beta." + System.getenv("GITHUB_RUN_NUMBER") // 2.3.1-beta.1000
	}
	return version + "+" + branchProvider.get() // 2.3.1-beta.1000+1.20.1
}.get()

dependencies {
	subprojects.forEach {
		api(project(path: ":$it.name", configuration: "namedElements"))
        include(project(":$it.name"))
	}
}

processResources {
	// exclude the template from the fat jar
	exclude("template.fabric.mod.json")
}

// resets the changelog and bumps the version after an automated release.
tasks.register("postRelease") {
	String nextVersion = project.hasProperty("nextVersion") ? project.property("nextVersion") : null
	File changelog = rootProject.file("CHANGELOG.txt")
	File props = rootProject.file("gradle.properties")
	String currentVersion = mod_version

	doFirst {
		if (nextVersion == null) {
			throw new RuntimeException("nextVersion property is not defined")
		}

		changelog.setText("")

		String properties = props.getText()
		properties = properties.replace(currentVersion, nextVersion)
		props.setText(properties)
	}
}

allprojects {
	if (name == "buildSrc") return

	apply plugin: "fabric-loom"
	apply plugin: PortingLibBuildPlugin

	group = "io.github.fabricators_of_create.Porting-Lib"

	version = versionNumber

	repositories {
		mavenCentral()
		maven { url = "https://maven.quiltmc.org/repository/release" }
		maven { url = "https://hephaestus.dev/release" }
		maven { url = "https://api.modrinth.com/maven" }
		maven { url = "https://maven.bai.lol" }
		maven { url = "https://maven.terraformersmc.com/releases/" }
		maven { url = "https://maven.parchmentmc.org" }
		maven { url = "https://maven.shedaniel.me/" }
		maven { url = "https://mvn.devos.one/releases/" }
		maven { url = "https://mvn.devos.one/snapshots/" }
		maven { url = "https://maven.wispforest.io" }
		maven { url = "https://cursemaven.com" }
		maven { url = "https://maven.vram.io" }
		maven {
			url = "https://jitpack.io"
			content {
				includeGroup("com.github.Chocohead")
			}
		}
		maven {
			url = "https://maven.jamieswhiteshirt.com/libs-release"
			content {
				includeGroup "com.jamieswhiteshirt"
			}
		}
	}

	dependencies {
		// dev environment
		minecraft("com.mojang:minecraft:$minecraft_version")
		mappings(loom.layered {
			it.officialMojangMappings { nameSyntheticMembers = false }
			if (parchment_version != "none") {
				String parchmentMinecraftVersion = minecraft_version;
				if (parchment_minecraft_version != "none")
					parchmentMinecraftVersion = parchment_minecraft_version;

				it.parchment("org.parchmentmc.data:parchment-$parchmentMinecraftVersion:$parchment_version@zip")
			}
		})
		modImplementation("net.fabricmc:fabric-loader:$loader_version")

		modCompileOnly("com.terraformersmc:modmenu:$modmenu_version") { exclude group: "net.fabricmc"; exclude group: "net.fabricmc.fabric-api" }
		modLocalRuntime("com.terraformersmc:modmenu:$modmenu_version") { exclude group: "net.fabricmc"; exclude group: "net.fabricmc.fabric-api" }

		// common dependencies
		// each module can also specify additional ones
		modImplementation("net.fabricmc.fabric-api:fabric-api:$fabric_api_version")

		implementation("javax.annotation:javax.annotation-api:1.3.2")
		implementation("com.google.code.findbugs:jsr305:3.0.2")

		if (mixin_extras_version != "none")
			include(implementation(annotationProcessor("io.github.llamalad7:mixinextras-fabric:${mixin_extras_version}")))
	}

	loom {
		runs.configureEach {
			ideConfigGenerated = true // loom doesn't gen runs for subprojects, unless this is set to true.
			vmArg("-Dmixin.debug.export=true") // export all mixins
//			vmArg("-Dmixin.debug.strict.unique=true") // strictly enforce that @Unique things are private
		}
	}

	configurations.configureEach {
		// fixes loom using a loader version from a dependency
		resolutionStrategy.force("net.fabricmc:fabric-loader:$loader_version")
	}

	processResources {
		Map<String, ?> properties = [
				version: version,
				loader_version: loader_version,
				fabric_api_version: fabric_api_version,
				minecraft_dependency: minecraft_dependency,
				java_version: sourceCompatibility,

				// property replacement is a bit too eager
				class_5124: "\$class_5124",
				class_56: "\$class_56",
                class_9665: "\$class_9665",
				class_7226: "\$class_7226",
				class_1793: "\$class_1793"
		]

		properties.forEach(inputs::property)

		if (project != rootProject) { // expand subproject FMJs. Must be done here for proper ordering.
			filesMatching("fabric.mod.json", new FmjExpander.Applicator(project))
		}

		filesMatching("fabric.mod.json") {
			expand properties
		}
	}

	jar.from(rootProject.file("LICENSE")) // copy license file into jar
}

subprojects {
	apply plugin: "maven-publish"

	archivesBaseName = "porting_lib_" + name

	loom {
		runs.configureEach {
			File output = file("src/main/resources/data/porting_lib_$name/structures/gametest")
			property("porting_lib.gametest.quickexport.output", output.absolutePath)
		}
		mods.register("porting_lib_" + name) {
			sourceSet sourceSets.main
		}
		File aw = file("src/main/resources/porting_lib_${name}.accesswidener")
		if (aw.exists())
			accessWidenerPath.set(aw)
	}

	// these two modules are used by all others automatically.
	if (name != "core" && name != "gametest") {
		portingLib {
			addModuleDependency("core") // core depends on gametest
		}
	}

	validateModule {
		projectName = project.name
		readMe.set(rootProject.file("README.md"))
		resources.set(project.file("src/main/resources"))
	}

	sortAccessWidener {
		File awFile = project.file("src/main/resources/${project.name}.accesswidener")
		if (awFile.exists())
			aw.set(awFile)
	}

	processResources {
		// include icon
		into("assets/porting_lib") {
			from(rootProject.file("src/main/resources/assets/porting_lib/icon.png"))
		}
	}

	java.withSourcesJar()

	publishing {
		repositories {
			maven {
				name = "devOS"
				String mavenType = System.getenv("RELEASE") == "true" ? "releases" : "snapshots"
				url = "https://mvn.devos.one/$mavenType/"
				credentials {
					username = System.getenv("MAVEN_USER")
					password = System.getenv("MAVEN_PASS")
				}
				authentication {
					register("basic", BasicAuthentication)
				}
			}
		}

		publications {
			register("mavenJava", MavenPublication) {
				from((SoftwareComponent) components["java"])
			}
		}
	}
}
