buildscript {
    repositories {
        gradlePluginPortal()
        maven {
            name = "Forge"
            url = "https://maven.minecraftforge.net"
        }
    }
    dependencies {
        classpath 'com.modrinth.minotaur:Minotaur:2.+'
        classpath 'gradle.plugin.org.jetbrains.gradle.plugin.idea-ext:gradle-idea-ext:1.1.7' // Required for NeoGradle
        classpath 'net.minecraftforge:gradleutils:2.2.0' // Required for changelog generation
    }
}

apply plugin: 'org.jetbrains.gradle.plugin.idea-ext'
apply plugin: 'net.minecraftforge.gradleutils'

changelog {
    fromTag '19.0.0'
}

ext {
    mod_version = gradleutils.getTagOffsetVersion()
    changelog_file = rootProject.file("build/changelog.txt")
    trimChangelog = (String text) -> {
        def m = text =~ /(?s) - (?:[0-9.]+) (.+?)(?=( - )|$)/
        return '```\n' + m[0][1].replaceAll(/(?m)^ */, '')
    }
}

allprojects {
    // Allow 400 errors.
    gradle.projectsEvaluated {
        tasks.withType(JavaCompile) {
            options.compilerArgs << "-Xmaxerrs" << "400"
        }
    }
}

subprojects {
    apply plugin: 'java'
    apply plugin: 'idea'
    apply plugin: 'maven-publish'

    if (!project.name.equals("Common")) {
        apply plugin: 'com.modrinth.minotaur'
    }

    version = "${minecraft_version}-${mod_version}"

    java.toolchain.languageVersion = JavaLanguageVersion.of(21)
    java.withSourcesJar()

    jar {
        manifest {
            attributes([
                'Specification-Title'     : mod_name,
                'Specification-Vendor'    : mod_authors,
                'Specification-Version'   : mod_version,
                'Implementation-Title'    : project.name,
                'Implementation-Version'  : mod_version,
                'Implementation-Vendor'   : mod_authors,
                'Implementation-Timestamp': new Date().format("yyyy-MM-dd'T'HH:mm:ssZ"),
                'Timestamp'               : System.currentTimeMillis(),
                'Built-On-Java'           : "${System.getProperty('java.vm.version')} (${System.getProperty('java.vm.vendor')})",
                'Build-On-Minecraft'      : minecraft_version
            ])
        }
    }

    repositories {
        mavenCentral()
        maven {
            name = 'Sponge / Mixin'
            url = 'https://repo.spongepowered.org/repository/maven-public/'
        }
        maven {
            name = 'Forge'
            url = "https://maven.minecraftforge.net"
        }
    }

    tasks.withType(JavaCompile).configureEach {
        it.options.encoding = 'UTF-8'
        it.options.release.set(21)
    }

    processResources {
        var expandProps = [
            minecraft_version   : minecraft_version,
            forge_version       : forge_version, forge_version_range: forge_version_range, forge_loader_version_range: forge_loader_version_range,
            neoforge_version    : neoforge_version, neoforge_version_range: neoforge_version_range, neoforge_loader_version_range: neoforge_loader_version_range,
            glitchcore_version  : glitchcore_version, terrablender_version: terrablender_version,
            mod_id              : mod_id, mod_name: mod_name, mod_display_name: mod_display_name, mod_version: mod_version,
            mod_authors         : mod_authors, mod_description: mod_description,
            mod_issues_url      : mod_issues_url, mod_page_url: mod_page_url, mod_git_url: mod_git_url,
            mod_discord_url     : mod_discord_url,
            mod_license         : mod_license
        ]
        filesMatching(['pack.mcmeta', 'fabric.mod.json', 'META-INF/mods.toml', 'META-INF/neoforge.mods.toml', "*.mixins.json"]) {
            expand expandProps
        }
        inputs.properties(expandProps)
    }

    // Disables Gradle's custom module metadata from being published to maven. The
    // metadata includes mapped dependencies which are not reasonably consumable by
    // other mod developers.
    tasks.withType(GenerateModuleMetadata) {
        enabled = false
    }

    afterEvaluate {
        // Share Modrinth configuration between loaders
        // Unfortunately the CurseForge plugin breaks when doing this
        // remapJar does not exist until after initial evaluation
        if (!name.equals("Common")) {
            modrinth {
                token = findProperty('modrinthToken')
                projectId = mod_modrinth_id
                versionNumber = mod_version
                versionName = "${mod_version} for ${name} ${minecraft_version}"
                versionType = release_channel
                uploadFile = name.equals("Fabric") ? remapJar : jar
                gameVersions = [minecraft_version]
                loaders = [name.toLowerCase()]
                dependencies {
                    if (name.equals("Fabric")) {
                        required.project "fabric-api"
                    }
                    required.project "glitchcore"
                    required.project "terrablender"
                }

                if (changelog_file.exists()) {
                    changelog = trimChangelog(changelog_file.text)
                }
            }
        }

        // archivesBaseName is not set until after initial evaluation
        publishing {
            publications {
                mavenJava(MavenPublication) {
                    artifactId project.archivesBaseName
                    groupId project.group
                    version project.version
                    from components.java

                    pom {
                        name = project.archivesBaseName
                        description = project.mod_description
                        url = project.mod_git_url
                        scm {
                            url = project.mod_git_url
                            connection = project.mod_scm_url
                            developerConnection = project.mod_scm_url
                        }
                        issueManagement {
                            system = 'github'
                            url = project.mod_issues_url
                        }
                        licenses {
                            license {
                                name = project.mod_license
                            }
                        }
                        developers {
                            developer {
                                id = 'adubbz'
                                name = 'Adubbz'
                            }
                            developer {
                                id = 'forstride'
                                name = 'Forstride'
                            }
                        }
                        withXml {
                            NodeList dependencies = asNode().dependencies
                            NodeList allDeps = dependencies.'*'

                            // Remove forge deps
                            allDeps.<Node> findAll() { Node el ->
                                el.artifactId.text() == 'forge' && el.groupId.text() == 'net.minecraftforge'
                            }.forEach() { Node el ->
                                el.parent().remove(el)
                            }
                            // Remove ForgeGradle's mapped suffix from versions & set as optional so anyone else doesn't inherit them
                            allDeps.<Node> findAll() { Node el ->
                                el.version.text().contains('_mapped_')
                            }.each { Node el ->
                                el.version.each { Node version ->
                                    def versionText = version.text()
                                    version.setValue(versionText.substring(0, versionText.indexOf('_mapped_')))
                                }
                                el.appendNode('optional', true)
                            }
                        }
                    }
                }
            }
            repositories {
                maven {
                    url = "https://maven.minecraftforge.net/releases/"
                    credentials {
                        username = System.getenv("MAVEN_USER")
                        password = System.getenv("MAVEN_PASSWORD")
                    }
                }
            }
        }
    }
}