buildscript {
    dependencies {
        classpath group: 'org.spongepowered', name: 'mixingradle', version: '0.7.+'
    }
}
plugins {
    id "idea"
    id "maven-publish"
    id "net.minecraftforge.gradle" version "5.1.+"
    id "com.matthewprenger.cursegradle" version "1.4.0"
}

apply plugin: 'org.spongepowered.mixin'
apply from: "minecraft.gradle"

def getGitRef() {
    try {
        final def stdout = new ByteArrayOutputStream()
        exec {
            commandLine "git", "rev-parse", "--short", "HEAD"
            standardOutput = stdout
        }
        return stdout.toString().trim()
    } catch (final Throwable ignored) {
        return "unknown"
    }
}

version = "${semver}+${getGitRef()}"
group = "li.cil.oc2"

java.toolchain.languageVersion = JavaLanguageVersion.of(17)

tasks.withType(JavaCompile).configureEach {
    options.encoding = "utf-8"
}

final def hasGithubPackageCredentials =
    (project.hasProperty("gpr.user") && project.hasProperty("gpr.key")) ||
        (System.getenv("GITHUB_ACTOR") && System.getenv("GITHUB_TOKEN"))

repositories {
    mavenCentral()
    maven {
        url 'https://cursemaven.com'
        content { includeGroup 'curse.maven' }
    }
    maven {
        url 'https://dvs1.progwml6.com/files/maven/'
        content { includeGroup 'mezz.jei' }
    }
    if (hasGithubPackageCredentials) {
        final def GithubPackages = [
            ["fnuecke/ceres", "li.cil.ceres"],
            ["fnuecke/sedna", "li.cil.sedna"],
            ["fnuecke/buildroot", "li.cil.sedna"]
        ]
        GithubPackages.each { final repo, final group ->
            maven {
                url = uri("https://maven.pkg.github.com/${repo}")
                credentials {
                    username = project.findProperty("gpr.user") ?: System.getenv("GPR_USER")
                    password = project.findProperty("gpr.key") ?: System.getenv("GPR_KEY")
                }
                content { includeGroup group }
            }
        }
    }
}

dependencies {
    minecraft "net.minecraftforge:forge:${minecraft_version}-${forge_version}"
    annotationProcessor "org.spongepowered:mixin:0.8.5:processor"

    // Specify the libs embedded in the library mod explicitly for local development, where
    // we can include these directly (and will have a local library mod using the local
    // versions). Can't get these to get properly resolved in the IDE otherwise (doesn't
    // pick them up via the library mod due to the embed configuration).
    if (hasGithubPackageCredentials) {
        compileOnly "li.cil.ceres:ceres:0.0.4"
        compileOnly "li.cil.sedna:sedna:2.0.8"
        compileOnly "li.cil.sedna:sedna-buildroot:0.0.8"
    }
    implementation "curse.maven:sedna-511276:3885542"

    implementation fg.deobf("curse.maven:markdownmanual-502485:3738124")

    compileOnly fg.deobf("mezz.jei:jei-${minecraft_version}:9.7.0.180:api")
    runtimeOnly fg.deobf("mezz.jei:jei-${minecraft_version}:9.7.0.180")

    testImplementation "org.mockito:mockito-inline:4.3.1"
    testImplementation "org.junit.jupiter:junit-jupiter-api:5.8.2"
    testRuntimeOnly "org.junit.jupiter:junit-jupiter-engine:5.8.2"
}

task packageScripts(type: Zip) {
    archiveFileName = "scripts.zip"
    destinationDirectory = file("$buildDir/resources/main/data/oc2/file_systems")
    from "src/main/scripts"
}

task copyLicensesToResources(type: Copy) {
    from "."
    into file("$buildDir/resources/main")
    include "LICENSE*"
}

processResources.dependsOn(packageScripts)
processResources.dependsOn(copyLicensesToResources)

minecraft {
    mappings channel: "official", version: minecraft_version

    accessTransformer = file("src/main/resources/META-INF/accesstransformer.cfg")

    runs {
        all {
            property "forge.logging.markers", "REGISTRIES"
            property "forge.logging.console.level", "info"

            mods {
                oc2 {
                    source sourceSets.main
                }
            }
        }

        client {
            workingDirectory project.file("run")
            property "forge.enabledGameTestNamespaces", "oc2"
        }

        server {
            workingDirectory project.file("run")
            property "forge.enabledGameTestNamespaces", "oc2"
            arg "--nogui"
        }

        gameTestServer {
            workingDirectory project.file('run')
            property "forge.enabledGameTestNamespaces", "oc2"
        }

        data {
            workingDirectory project.file("run")
            args "--mod", "oc2", "--all", "--output", file("src/generated/resources/"), "--existing", file("src/main/resources")
        }
    }
}

mixin {
    add sourceSets.main, "mixins.oc2.refmap.json"
    config "mixins.oc2.json"

//    quiet
}

task copyGeneratedResources(type: Copy) {
    from "src/generated"
    into "src/main"
    exclude "resources/.cache"
}

jar {
    finalizedBy "reobfJar"

    manifest {
        attributes([
            "FMLAT"                   : "accesstransformer.cfg",
            "Specification-Title"     : "oc2",
            "Specification-Vendor"    : "Sangar",
            "Specification-Version"   : "1",
            "Implementation-Title"    : project.name,
            "Implementation-Version"  : "${semver}",
            "Implementation-Vendor"   : "Sangar",
            "Implementation-Timestamp": new Date().format("yyyy-MM-dd'T'HH:mm:ssZ"),
            "MixinConfigs"            : "mixins.oc2.json",
        ])
    }
}

task apiJar(type: Jar) {
    archiveClassifier.set("api")
    from sourceSets.main.allSource
    from sourceSets.main.output
    include "li/cil/oc2/api/**"
}

artifacts {
    archives apiJar
}

publishing {
    publications {
        mavenJava(MavenPublication) {
            groupId = project.group
            artifactId = project.name
            version = semver
            artifact jar
            artifact apiJar
        }
    }
    repositories {
        maven {
            name = "GitHubPackages"
            url = System.getenv("GITHUB_MAVEN_URL") ?: ""
            credentials {
                username = System.getenv("GITHUB_ACTOR")
                password = System.getenv("GITHUB_TOKEN")
            }
        }
    }
}

curseforge {
    apiKey = System.getenv("CURSEFORGE_API_KEY") ?: ""
    project {
        id = curse_project_id
        releaseType = System.getenv('CURSEFORGE_RELEASE_TYPE') ?: "alpha"
        changelogType = 'markdown'
        changelog = System.getenv("CHANGELOG") ?: "Changelog not available."
        addGameVersion "Forge"
        addGameVersion minecraft_version
        addGameVersion "Java 17"
        relations {
            requiredDependency "markdownmanual"
            requiredDependency "sedna"
        }
    }
}

idea {
    module {
        for (final String exclude in ["assets", "run", "out", "logs", "src/generated"]) {
            excludeDirs += file(exclude)
        }
    }
}

test {
    useJUnitPlatform()
}
