buildscript {
	repositories {
		jcenter()
		maven {
			name = 'forge'
			url = 'http://files.minecraftforge.net/maven'
		}
		maven {
			url 'https://plugins.gradle.org/m2/'
		}
	}
	dependencies { 
		classpath 'net.minecraftforge.gradle:ForgeGradle:2.3-SNAPSHOT'
	}
}

//Returns whether the private keystore for signing is available and if the jar should be signed
project.ext.canJarBeSigned = {
	return getVariable('blKeyStore') != null && (!isDeploymentEnv || isDeploymentRelease)
}

//Returns the public fingerprint, may be empty ("")
project.ext.getProjectFingerprint = {
	if(canJarBeSigned()) {
		return getVariable('blKeyStoreFingerprint').replaceAll(':', '').toLowerCase()
	}
	return ''
}

//Returns the current version by reading directly from the ModInfo.java file
project.ext.getVersionFromJava = {
	String major = '0';
	String revision = '0';
	String patch = '0';
	String prefix = 'public static final String VERSION = "';
	File file = file('src/main/java/thebetweenlands/common/lib/ModInfo.java')
	file.eachLine { String s ->
		s = s.trim();
		if (s.startsWith(prefix)) {
			s = s.substring(prefix.length(), s.length() - 2);
			String[] pts = s.split('\\.');

			major = pts[0];
			revision = pts[1];
			patch = pts[2];
		}
	}

	return "$major.$revision.$patch";
}

//Returns the mod ID by reading directly from the ModInfo.java file
project.ext.getModIdFromJava = {
	String id = 'N/A';
	String prefix = 'public static final String ID = "';
	File file = file('src/main/java/thebetweenlands/common/lib/ModInfo.java')
	file.eachLine { String s ->
		s = s.trim();
		if (s.startsWith(prefix)) {
			id = s.substring(prefix.length(), s.length() - 2);
		}
	}

	return "$id";
}

//Attempts to get a project variable and if none is found it tries to read from a system environment variable
project.ext.getVariable = { key ->
	return project.hasProperty(key) ? project.property(key) : ENV[key];
}

project.ext.ENV = System.getenv()
project.ext.isDeploymentEnv = ENV['DEPLOY_ENV'] != null && 'true'.equals(ENV['DEPLOY_ENV'])
project.ext.isDeploymentRelease = project.isDeploymentEnv && ENV['DEPLOY_BUILD_TYPE'] != null && 'release'.equals(ENV['DEPLOY_BUILD_TYPE'])
project.ext.buildnumber = project.isDeploymentEnv ? ENV['DEPLOY_BUILD_NUMBER'] : ''

project.ext.modid = project.getModIdFromJava()

allprojects {
	version = project.getVersionFromJava()
	if(!isDeploymentRelease) version = version + (!project.isDeploymentRelease ? ((project.isDeploymentEnv ? ('-' + project.buildnumber) : '') + '-SNAPSHOT') : '')

	apply plugin: 'net.minecraftforge.gradle.forge'
	
	minecraft {
		version = "1.12.2-14.23.5.2773"
		runDir = 'minecraft'
		replace '${version}', project.version
		replace '${mcversion}', project.minecraft.version
		replace '/*!ide*/true/*ide!*/', 'false'
		replace '${fingerprint}', getProjectFingerprint()
		clientJvmArgs = ['-Dfml.coreMods.load=thebetweenlands.core.TheBetweenlandsLoadingPlugin']
		serverJvmArgs = ['-Dfml.coreMods.load=thebetweenlands.core.TheBetweenlandsLoadingPlugin']

		// the mappings can be changed at any time, and must be in the following format.
		// snapshot_YYYYMMDD   snapshot are built nightly.
		// stable_#            stables are built at the discretion of the MCP team.
		// Use non-default mappings at your own risk. they may not allways work.
		// simply re-run your setup task after changing the mappings to update your workspace.
		mappings = "stable_39"
		makeObfSourceJar = false // an Srg named sources jar is made by default. uncomment this to disable.
	}
	
	apply from: new File(rootProject.projectDir, 'dependencies.gradle')
}

//Don't build jar for root project
tasks.remove(tasks.build)

subprojects {
	//Don't set up dev env for subprojects
	tasks.remove(tasks.setupCiWorkspace)
	tasks.remove(tasks.setupDevWorkspace)
	tasks.remove(tasks.setupDecompWorkspace)
	tasks.remove(tasks.eclipse)
	tasks.remove(tasks.idea)

	archivesBaseName = 'TheBetweenlands'
	sourceCompatibility = targetCompatibility = '1.8'

	group = 'angrypixel'

	//Move build dir into root's build folder
	buildDir = new File(rootProject.projectDir, 'build/' + project.name + '/build/')

	//Set sourceSets.main to root's sourceSets.main
	sourceSets {
		main {
			java {
				srcDir new File(rootProject.projectDir, 'src/main/java')
			}
			resources {
				srcDir new File(rootProject.projectDir, 'src/main/resources')
			}
		}
	}

	//Processes the resources of sourceSets.main
	processResources {
		inputs.property 'version', project.version
		inputs.property 'mcversion', project.minecraft.version

		from (sourceSets.main.resources.srcDirs) {
			include 'mcmod.info'
			expand 'version':project.version, 'mcversion':project.minecraft.version
		}

		from (sourceSets.main.resources.srcDirs) { exclude 'mcmod.info' }
		rename '(.+_at.cfg)', 'META-INF/$1'
	}

	//Set destination dir of all subprojects to build/libs/
	jar {
		destinationDir = new File(rootProject.projectDir, 'build/libs/')
	}

	//Adds the maven artifact attribute to the specified Manifest
	project.ext.addMavenArtifactAttribute = { m, classifier ->
		m.attributes ([
			'Maven-Artifact': group + ':' + archivesBaseName + ':' + project.version + ':' + classifier,
			'Timestamp': new java.util.Date().getTime()
		])
	}
}

apply plugin: 'idea'
idea.project.modules = new ArrayList([rootProject.idea.module])

if(isDeploymentEnv) println('Deployment environment found')
if(isDeploymentRelease) println('Deploying a release build')

println(canJarBeSigned() ? 'Keystore properties found, jar files will be signed' : 'No keystore properties found, jar files will not be signed')

println('Building version ' + version)

apply from: 'projects.gradle'