// Build repositories
buildscript {
	repositories {
		maven { url = 'https://maven.minecraftforge.net' }
		maven {
			name = "sonatype releases"
			url = "https://oss.sonatype.org/content/repositories/releases/"
		}
		maven {
			name = "sonatype snapshots"
			url = "https://oss.sonatype.org/content/repositories/snapshots/"
		}
        maven {
            name = "sponge"
            url = "https://repo.spongepowered.org/repository/maven-public/"
        }
		mavenCentral()
		mavenLocal()
	}
	dependencies {
		classpath "org.jfrog.buildinfo:build-info-extractor-gradle:3.0.1"
		classpath "org.ajoberstar:gradle-git:0.12.0"
		classpath("com.diffplug.gradle:goomph:3.42.2")
 		classpath files('lib/plugins/mixingradle-0.7.39.jar')//built from https://github.com/CreativeMD/MixinGradle/tree/task_fix
	}
}

plugins {
    id 'idea'
    id 'com.diffplug.eclipse.apt' version '3.35.0'
    id 'org.sonarqube' version '2.5'
    id "com.matthewprenger.cursegradle" version "1.4.0"
    id "com.modrinth.minotaur" version "2.+"
    id 'net.minecraftforge.gradle' version '5.1.+'
    id 'com.github.johnrengelman.shadow' version '7.1.2'
}
apply plugin: 'jacoco'
apply plugin: 'org.spongepowered.mixin'

sonarqube {
    properties {
        properties['sonar.projectKey'] = "com.forgeessentials:forgeessentials"
        properties['sonar.projectName'] = project.mod_name
        properties['sonar.projectVersion'] = project.mod_base + "." + project.mod_major
    }
}

// Set up FE required repositories
repositories {
    flatDir {
        dirs 'lib'
    }

	maven {
		name = "CurseForge"
		url = "https://minecraft.curseforge.com/api/maven/"
	}

	maven {
		name = "sk89q"
		url = "https://maven.enginehub.org/repo/"
	}

	maven {
		name = "sponge"
		url = "https://repo.spongepowered.org/maven/"
	}

    maven {
        name 'JEI'
        url "https://dvs1.progwml6.com/files/maven"
        content {
            includeGroup 'mezz.jei'
        }
		allowInsecureProtocol = true
    }

    maven {
        name = "forge"
        url = "https://files.minecraftforge.net/maven"
    }

	maven {
		name "Sonatype (Cubic Chunks)"
		url "https://oss.sonatype.org/content/repositories/public/"
	}
}
/************************************************************
 * General configuration
 */

// Get buildNumber from environment variable
ext.buildNumber = "DEV"
if (System.getenv("BUILD_NUMBER") != null) {
	buildNumber = System.getenv("BUILD_NUMBER")
}
// Make numeric build number in case of dev enviroment so forge does not have a heart attack
ext.buildNumberNumber = "0"
if (buildNumber != "DEV"){
	buildNumberNumber = buildNumber
}

ext.set 'changelog', System.getenv("CHANGE_LOG")
ext.set 'releaseType', 'beta'

// Get commit hash

import com.github.jengelman.gradle.plugins.shadow.tasks.ShadowJar
import org.apache.tools.ant.filters.ReplaceTokens
import org.ajoberstar.grgit.Grgit
def repo = Grgit.open(project.file("."))
ext.gitCommitHash = repo.log().find().abbreviatedId

// Set build properties
version = "$mod_base.$mod_major.$buildNumber"
group = "com.forgeessentials"
archivesBaseName = "forgeessentials"
sourceCompatibility = 1.8
targetCompatibility = 1.8
//java.toolchain.languageVersion = JavaLanguageVersion.of(8) // Mojang ships Java 8 to end users, so your mod should target Java 8.
println('Java: ' + System.getProperty('java.version') + ' JVM: ' + System.getProperty('java.vm.version') + '(' + System.getProperty('java.vendor') + ') Arch: ' + System.getProperty('os.arch'))
println('Running Tasks: ' +project.gradle.startParameter.taskNames)

ext.set 'srcFile',file("./tmp/$archivesBaseName-$minecraftVersion-$mod_base.$mod_major.$buildNumber-server.jar")
ext.set 'chatSrcFile',file("./tmp/$archivesBaseName-$minecraftVersion-$mod_base.$mod_major.$buildNumber-chatAddon.jar")
ext.set 'clientSrcFile',file("./tmp/$archivesBaseName-$minecraftVersion-$mod_base.$mod_major.$buildNumber-client.jar")

curseforge {
    apiKey = System.getenv("CF_APIKEY")
    if (apiKey) {
        project {
            id = projectID
            changelog = project.changelog
            releaseType = project.releaseType
            addGameVersion minecraftVersion
            addGameVersion 'Forge'
            addGameVersion 'Java 8'

            mainArtifact(project.srcFile) {
                displayName = "$archivesBaseName-$minecraftVersion-$mod_base.$mod_major.$buildNumber"
                relations {
                    optionalDependency 'baubles'
                }
            }

            addArtifact project.chatSrcFile
        }
        project {
            id = clientProjectID
            changelog = project.changelog
            releaseType = project.releaseType
            addGameVersion minecraftVersion
            addGameVersion 'Forge'
            addGameVersion 'Java 8'

            mainArtifact(project.clientSrcFile) {
                displayName = "$archivesBaseName-$minecraftVersion-$mod_base.$mod_major.$buildNumber"
                relations {
                    tool('forge-essentials')
                }
            }
        }
    }
    options {
        javaVersionAutoDetect = false
        forgeGradleIntegration = false
        javaIntegration = false
    }
}

modrinth {
    token = System.getenv("MODRINTH_TOKEN")
    projectId = "forge-essentials"
    versionNumber = "$mod_base.$mod_major.$buildNumber"
    versionType = project.releaseType
    versionName = "$archivesBaseName-$minecraftVersion-$mod_base.$mod_major.$buildNumber"
    uploadFile = project.srcFile
    gameVersions = [minecraftVersion]
    additionalFiles = [project.chatSrcFile]
    loaders = ["forge"]
    changelog = project.changelog
}

project.afterEvaluate {
    var task = tasks.findByPath("modrinth")
    task?.dependsOn = []
    task = tasks.findByPath("curseforge$projectID")
    task?.dependsOn = []
    task = tasks.findByPath("curseforge$clientProjectID")
    task?.dependsOn = []
}

// Set up forge options
minecraft {
	mappings channel: 'official', version: '1.16.5'
    //accessTransformer = file('src/main/resources/META-INF/forgeessentials_at.cfg')
    runs {
	    client {
	            workingDirectory project.file('rundir')

	            // Recommended logging data for a userdev environment
	            property 'forge.logging.markers', 'SCAN,REGISTRIES,REGISTRYDUMP'

	            // Recommended logging level for the console
	            property 'forge.logging.console.level', 'debug'

	            mods {
	            }
	        }
        server {
            workingDirectory project.file('rundir')

            // Recommended logging data for a userdev environment
            property 'forge.logging.markers', 'SCAN,REGISTRIES,REGISTRYDUMP'

            // Recommended logging level for the console
            property 'forge.logging.console.level', 'debug'

            mods {
            }
        }
    }
}

// Configure shared manifest
ext.sharedManifest = manifest {
	attributes (
		"BuildID": gitCommitHash,
		"BuildNumber": buildNumber,
		"FMLCorePluginContainsFMLMod": "true",
		"ForceLoadAsMod": "true",
        "Specification-Title": "forgeessentials",
        "Specification-Vendor": "forgeessentials",
        "Specification-Version": "1", // We are version 1 of ourselves
        "Implementation-Title": project.name,
        "Implementation-Version": "$mod_base.$mod_major",
        "Implementation-Vendor" :"forgeessentials",
        "Implementation-Timestamp": new Date().format("yyyy-MM-dd'T'HH:mm:ssZ")
	)
}

ext.serverManifest = manifest {
	from sharedManifest
	attributes (
		"MixinConfigs": "mixins.forgeessentials.json",
		"FMLAT": "forgeessentials_at.cfg"
	)
}

ext.clientManifest = manifest {
	from sharedManifest
	attributes (
		"MixinConfigs": "mixins.forgeessentials.client.json"
	)
}

// Configure shared manifest
ext.chatAddonManifest = manifest {
	from sharedManifest
	attributes (
		"MixinConfigs": "",
		"Implementation-Title": "forgeessentials-Chat-Addon"
	)
}
/************************************************************
 * Dependency configuration
 */

// Create dependency configurations
configurations {
	clientannotationProcessor
	serverannotationProcessor
	shadowLib
	//shadowClientLib
	shadowchataddonLib
	compile.extendsFrom buildDep, shadowLib, shadowchataddonLib//, serverLib, shade, shadeClient
	chataddonCompile.extendsFrom compile
}

// def jdkHome = System.getenv("JAVA_HOME")

// Configure dependencies (build-only, shaded and packed libraries)
dependencies {

    minecraft "net.minecraftforge:forge:$project.minecraftVersion-$project.forgeVersion"
	 // IRC
	implementation "org.pircbotx:pircbotx:2.1"
	shadowchataddonLib("org.pircbotx:pircbotx:2.1") {
        // these are all packaged with the minecraft server jar
        exclude module: 'guava'
        exclude module: 'commons-lang3'
        exclude module: 'commons-codec'
    }

	implementation 'net.dv8tion:JDA:5.0.0-beta.8'
	shadowchataddonLib('net.dv8tion:JDA:5.0.0-beta.8')

	// Database libraries
	shadowLib group: 'com.h2database', 	name: 'h2', 					version: '1.3.175'
	shadowLib group: 'mysql', 			name: 'mysql-connector-java', 	version: '5.1.22'
	//org.hibernate
	implementation 'org.hibernate:hibernate-core:5.6.15.Final'
	implementation 'javax.persistence:javax.persistence-api:2.2'
	shadowLib group: 'org.hibernate', 	  name: 'hibernate-core', 		version: '5.6.15.Final'
	//shadowLib group: 'javax.persistence', name: 'javax.persistence-api', version: '2.2'
	compileOnly   group: 'org.hibernate', 	  name: 'hibernate-jpamodelgen',version: '5.6.15.Final'

	//annonations processor
	serverannotationProcessor 'org.spongepowered:mixin:0.8.5:processor'
	serverannotationProcessor 'org.hibernate:hibernate-jpamodelgen:5.6.15.Final'
	clientannotationProcessor 'org.spongepowered:mixin:0.8.5:processor'
	
	// WorldEdit
	implementation 'com.sk89q.worldedit:worldedit-core:7.2.6-SNAPSHOT'
	implementation 'com.sk89q.worldedit:worldedit-forge-mc1.16.3:7.2.6-SNAPSHOT'

	implementation "baubles:baubles:1.8.7.1:1.16.5"

	implementation 'org.spongepowered:spongeapi:8.0.0'
	compileOnly ("io.github.opencubicchunks:cubicchunks-api:1.12.2-0.0-SNAPSHOT") {
		exclude group: "org.spongepowered", module: "mixin"
	}
	//compileOnly "com.feed_the_beast.mods:FTBLib:5.4.7.2"
	//compileOnly "com.feed_the_beast.mods:FTBUtilities:5.4.1.131"

	// TOOLS.jar from jdk for javadoc support
	implementation files(System.getenv("JAVA_HOME") + "/lib/tools.jar")
	
	//dependicies for chat addon
	chataddonCompile sourceSets.main.output
}

/************************************************************
 * Configure source sets (e.g., src/main)
 */

sourceSets {
    def deps = [
		configurations.minecraft,
		configurations.compile,
		configurations.compileClasspath,
		configurations.runtimeClasspath
	]
	utils {
		compileClasspath = files(deps)
	}
	main {
		compileClasspath += files(sourceSets.utils.compileClasspath, sourceSets.utils.output)
        ext.refMap = "mixins.forgeessentials.refmap.json"
	}
	client {
		compileClasspath += files(sourceSets.main.compileClasspath)
        ext.refMap = "mixins.forgeessentials.client.refmap.json"
	}
	chataddon {
		compileClasspath += files(sourceSets.main.compileClasspath, configurations.chataddonCompile)
	}
	utils {
		if(project.gradle.startParameter.taskNames.contains("genintellijruns")||project.gradle.startParameter.taskNames.isEmpty()) {
			compileClasspath = files(sourceSets.main.compileClasspath)
		}
	}
}

// Configure utils tokens
task processSource(type: Sync) {
    from sourceSets.utils.java
    filter(ReplaceTokens, tokens: ['_MCVERSION_':project.minecraftVersion, '_BASEVERSION_': project.mod_base, '_MAJORVERSION_': project.mod_major, '_RELEASETYPE_': project.releaseType])
    into "$buildDir/src"
}

project.compileUtilsJava {
	source = processSource.outputs
}
project.compileChataddonJava {
	source = files(sourceSets.main.compileClasspath, sourceSets.chataddon.java)
}

// Configure server resource processing
project.processResources {
	from (sourceSets.main.resources.srcDirs) {
		include 'META-INF/mods.toml'
		duplicatesStrategy = DuplicatesStrategy.INCLUDE
		expand (
			'version': "$mod_base.$mod_major.$buildNumberNumber",
			'mod_name': mod_name
		)
	}
}

// Configure client resource processing
project.processClientResources {
	from (sourceSets.client.resources.srcDirs) {
		include 'META-INF/mods.toml'
		duplicatesStrategy = DuplicatesStrategy.INCLUDE
		expand (
			'version': "$mod_base.$mod_major.$buildNumberNumber",
			'mod_name': mod_name_client
		)
	}
}

// Configure chataddon resource processing
project.processChataddonResources {
	from (sourceSets.chataddon.resources.srcDirs) {
		include 'META-INF/mods.toml'
		duplicatesStrategy = DuplicatesStrategy.INCLUDE
		expand (
			'version': "$mod_base.$mod_major.$buildNumberNumber",
			'mod_name': mod_name_chatAddon
		)
	}
}

mixin {
    add sourceSets.main, "mixins.forgeessentials.refmap.json"
    add sourceSets.client, "mixins.forgeessentials.client.refmap.json"

    config 'mixins.forgeessentials.json'
    config 'mixins.forgeessentials.client.json'
    disableTargetValidator = false
    overwriteErrorLevel = 'error'
}

compileJava {
    options.annotationProcessorPath = configurations.serverannotationProcessor
}
compileClientJava {
    options.annotationProcessorPath = configurations.clientannotationProcessor
}
/************************************************************
 * Configure tsd jar
 */

 // JavaExec task for generating tsd
//  Calls the main class for the TSD generator since that is working

task tsd(type: JavaExec) {
    dependsOn "classes"
    classpath = files(project.sourceSets.test.compileClasspath, project.sourceSets.main.compileClasspath)
    mainClass = "com.forgeessentials.jscripting.TsdGenerator"
    doLast {
        copy {
            from files("jscripting/") {
                include "*.d.ts"
            }
			duplicatesStrategy = DuplicatesStrategy.INCLUDE
            into "build/resources/main/com/forgeessentials/jscripting"
        }
    }
}

/************************************************************
 * Configure client jar
 */
task clientJar (dependsOn: ["clientClasses"], type: Jar) {
	archiveClassifier = "client"
	archiveAppendix = project.minecraftVersion

	from sourceSets.client.output
	from sourceSets.utils.output
	duplicatesStrategy = DuplicatesStrategy.INCLUDE

	exclude 'mixins.forgeessentials.refmap.json'
	manifest {
		from clientManifest
	}
}
/************************************************************
 * Configure shadow jar
 */

shadowJar {
	dependsOn clientJar
	minimize {
 	   exclude(dependency('org.hibernate:.*:.*'))
 	   exclude(dependency('mysql:.*:.*'))
 	   exclude(dependency('com.h2database:.*:.*'))
 	   exclude(dependency('javax:.*:.*'))
 	}
	relocate  'org.hibernate','com.forgeessentials.thirdparty.org.hibernate'
	relocate  'org.h2','com.forgeessentials.thirdparty.org.h2'
	relocate  'org.jboss','com.forgeessentials.thirdparty.org.jboss'
	relocate  'javax.persistence','com.forgeessentials.thirdparty.javax.persistence'
	relocate  'javax.transaction','com.forgeessentials.thirdparty.javax.transaction'
	relocate  'javax.activation','com.forgeessentials.thirdparty.javax.activation'
	relocate  'antlr','com.forgeessentials.thirdparty.antlr'
	//relocate  'com.fasterxml','com.forgeessentials.thirdparty.com.fasterxml'
	relocate  'com.mysql','com.forgeessentials.thirdparty.com.mysql'
	configurations = [project.configurations.shadowLib]
	archiveClassifier = "shadow"

	from sourceSets.main.output
	from sourceSets.utils.output
	exclude('com/forgeessentials/client/**')
}

/************************************************************
 * Configure server jar (default)
 */

jar {
	duplicatesStrategy = DuplicatesStrategy.INCLUDE
	dependsOn clientJar
	dependsOn shadowJar
    dependsOn "tsd"
    archiveClassifier = "server"
	archiveAppendix = project.minecraftVersion
	
	from sourceSets.main.output
	from sourceSets.utils.output
    exclude('com/forgeessentials/client/**')

	from (zipTree(shadowJar.archiveFile)) {
		exclude 'META-INF','META-INF/**'
		exclude 'assets/**'
		exclude '.gitkeep'
		exclude 'about.html'
		exclude 'plugin.properties'
	}

	from (zipTree(shadowJar.archiveFile)) {
		include 'META-INF/services/*'
	}

	exclude('mixins.forgeessentials.client.refmap.json')
	exclude('mapper_colorscheme.txt')
	manifest {
		from serverManifest
	}
}
jar.doLast {
	delete (shadowJar.archiveFile)
	delete (processSource.outputs)
	delete (annotations.archiveFile)
}

/************************************************************
 * Configure addon jars
 */
 
task chataddonshadowJar(type: ShadowJar) {
	minimize()
	description = "ShadowJar for chatAddon code"
	archiveClassifier = 'shadowChatAddon'
	from sourceSets.chataddon.output
	configurations = [project.configurations.shadowchataddonLib]
}

task chataddonJar(dependsOn: ["classes", "chataddonshadowJar"], type: Jar) {
	archiveClassifier = "chatAddon"
	archiveAppendix = project.minecraftVersion

	from sourceSets.chataddon.output
	duplicatesStrategy = DuplicatesStrategy.INCLUDE

	from (zipTree(chataddonshadowJar.archiveFile)) {
		exclude 'META-INF','META-INF/**'
		exclude 'assets/**'
		exclude 'natives','natives/**'
		exclude 'about.html'
		exclude 'plugin.properties'
	}
	exclude('mixins**')
	exclude('FeRemote.jks')
	exclude('META-INF/forgeessentials_at.cfg')
	exclude('META-INF/persistence.xml')
	exclude('mapper_colorscheme.txt')
	exclude('module-info.class')
	manifest {
		from chatAddonManifest
	}
}
chataddonJar.doLast {
	delete (chataddonshadowJar.archiveFile)
}

/************************************************************
 * Deobfuscated server jar
 * Dependency name for maven = com.forgeessentials:forgeessentials:<version>:
 * */

task deobfJar(dependsOn: "classes", type: Jar) {
	archiveClassifier = "dev-"+gitCommitHash
	archiveAppendix = project.minecraftVersion
	
	from sourceSets.main.output
	from sourceSets.utils.output
	
	from (sourceSets.main.java) {
		into ("src/")
	}

	manifest {
		from serverManifest
	}
}
//
//task sourceJar(type: Jar) {
//	classifier = "sources"
//	appendix = project.minecraftVersion
//
//	from sourceSets.main.allSource
//
//	manifest {
//		from serverManifest
//	}
//}


/************************************************************
 * Configure API javadoc
 */
/*
javadoc {
	include "com/forgeessentials/api/**"
	classpath = sourceSets.main.compileClasspath + sourceSets.main.output
	options.addBooleanOption("Xdoclint:reference,accessibility,html", true) // excluded: syntax, missing
}

task javadocJar(type: Jar, dependsOn: javadoc) {
	classifier = "javadoc"
	appendix = project.minecraftVersion
	
	from javadoc.destinationDir
	
	manifest { from sharedManifest }
}*/

/************************************************************
 * Configure Annotations for IDEs Jar
 */
task annotations(type: Jar) {
	archiveClassifier = "annonations"
	archiveAppendix = project.minecraftVersion
	
    from(sourceSets.main.output) {
        include "com/forgeessentials/playerlogger/entity/**"
        exclude "com/forgeessentials/playerlogger/entity/Action.class"
        exclude "com/forgeessentials/playerlogger/entity/Action01Block\$ActionBlockType.class"
        exclude "com/forgeessentials/playerlogger/entity/Action01Block.class"
        exclude "com/forgeessentials/playerlogger/entity/Action02Command.class"
        exclude "com/forgeessentials/playerlogger/entity/Action03PlayerEvent\$PlayerEventType.class"
        exclude "com/forgeessentials/playerlogger/entity/Action03PlayerEvent.class"
        exclude "com/forgeessentials/playerlogger/entity/Action04PlayerPosition.class"
        exclude "com/forgeessentials/playerlogger/entity/BlockData.class"
        exclude "com/forgeessentials/playerlogger/entity/PlayerData.class"
        exclude "com/forgeessentials/playerlogger/entity/WorldData.class"
    }
}
task copyJarToGenerated(type: Copy) {
    from annotations
    into "misc/"
}
annotations.finalizedBy copyJarToGenerated

/************************************************************
 * Others
 */

reobf {
	jar{}
    clientJar{}
    chataddonJar{}
}

 // Add default artifacts for task "build"
artifacts {
	archives deobfJar
	archives clientJar
	archives chataddonJar
	archives annotations
}
