sourceSets.main.java.srcDirs = ["src/"]

project.ext.mainClassName = "mindustry.desktop.DesktopLauncher"
project.ext.assetsDir = new File("../core/assets")

def enableTemplates = true
def JDK_DIR = "$System.env.JDK_DIR"
def ICON_DIR = new File("$rootDir/core/assets/icons/icon.icns")
def platforms = ["Linux64", "Windows64", "Windows32", "MacOS"]

task run(dependsOn: classes, type: JavaExec){
    mainClass = project.mainClassName
    classpath = sourceSets.main.runtimeClasspath
    standardInput = System.in
    workingDir = project.assetsDir
    ignoreExitValue = true

    if(System.getProperty("os.name").toLowerCase().contains("mac")){
        jvmArgs("-XstartOnFirstThread")
    }

    jvmArgs += "-XX:+ShowCodeDetailsInExceptionMessages"

    if(project.hasProperty("args")){
        args Eval.me(project.getProperties()["args"])
    }

    if(project.hasProperty("jvmArgs")){
        jvmArgs((List<String>)Eval.me(project.getProperties()["jvmArgs"]))
    }

    if(project.hasProperty("dataDir")){
        environment("MINDUSTRY_DATA_DIR", project.getProperties()["dataDir"])
    }

    if(args.contains("debug")){
        mainClass = "mindustry.debug.DebugLauncher"
    }
}

task dist(type: Jar, dependsOn: configurations.runtimeClasspath){
    dependsOn ":desktop:processResources"

    from files(sourceSets.main.output.classesDirs)
    from files(sourceSets.main.output.resourcesDir)
    from {configurations.runtimeClasspath.collect{ it.isDirectory() ? it : zipTree(it) }}
    from files(project.assetsDir)
    exclude("config/**")
    duplicatesStrategy = DuplicatesStrategy.EXCLUDE

    //don't include steam shared libraries unless necessary
    if(!versionModifier.contains("steam")){
        exclude("**steam**.so", "**steam**.dll", "**steam**.dylib")
    }

    archiveFileName = "${appName}.jar"

    manifest{
        attributes 'Main-Class': project.mainClassName
        //note: this doesn't do anything when launched from the bundled JVM
        attributes 'Enable-Native-Access': 'ALL-UNNAMED'
    }
}

if(!project.ext.hasSprites() && System.getenv("JITPACK") != "true"){
    println "Scheduling sprite packing."
    run.dependsOn ":tools:pack"
    dist.dependsOn ":tools:pack"
}

//this is only for local testing
//add -Prelease -PversionModifier=steam as build properties
task steamtest(dependsOn: dist){
    doLast{
        copy{
            from "build/libs/Mindustry.jar"
            if(project.hasProperty("destination")){
                into project.property("destination")
            }else if(System.properties["os.name"].contains("Mac")){
                into "/Users/anuke/Library/Application Support/Steam/steamapps/common/Mindustry/Mindustry.app/Contents/Resources"
            }else{
                into "/home/anuke/.steam/steam/steamapps/common/Mindustry/jre"
            }
            rename("Mindustry.jar", "desktop.jar")
        }
    }
}

//required templates:
//- Windows32: Not provided by Packr! This uses Java 8
//required JDKs:
//- Windows64
//- Linux64
//- Mac
platforms.each{ platform ->
    task "packr${platform.toString()}"{
        dependsOn dist

        doLast{
            copy{
                into "build/packr/"
                rename("${appName}.jar", "desktop.jar")
                from "build/libs/${appName}.jar"
            }

            delete{
                delete "build/packr/output/"
            }

            //the Windows32 version uses an old java-8 based template, because packr and jpackage don't support win32
            if(enableTemplates && (platform == "Windows32")){
                copy{
                    into "build/packr/output"
                    from "${JDK_DIR}/templates/${platform.toString().toLowerCase()}"
                }

                copy{
                    into "build/packr/output/jre"
                    rename("${appName}.jar", "desktop.jar")
                    from "build/libs/${appName}.jar"
                }
            }else{
                def jarPath = JDK_DIR + "packr.jar"
                def args = new String[]{"java", "-jar", jarPath}

                args += new String[]{
                        "--platform", platform == "MacOS" ? "Mac" : platform.toString(),
                        "--jdk", JDK_DIR + "jre-${platform.toString().toLowerCase()}",
                        "--executable", appName,
                        "--classpath", "$rootDir/desktop/build/packr/desktop.jar".toString(),
                        "--mainclass", project.ext.mainClassName,
                        "--verbose",
                        "--bundle", getPackage() + ".mac",
                        "--icon", ICON_DIR,
                        "--output", "$rootDir/desktop/build/packr/output".toString(),
                        "--removelibs", "$rootDir/desktop/build/packr/desktop.jar".toString()
                }

                args += "--vmargs"

                if(platform == "MacOS"){
                    args += "XstartOnFirstThread"
                }

                args += "Dhttps.protocols=TLSv1.2,TLSv1.1,TLSv1"
                args += "XX:+ShowCodeDetailsInExceptionMessages"
                args += "XX:+UseCompactObjectHeaders"
                args += "enable-native-access=ALL-UNNAMED"

                exec{
                    commandLine args.toList()
                    standardOutput = System.out
                }

                def outputJsonFile = platform != "MacOS" ? file("build/packr/output/Mindustry.json") : file("build/packr/output/${appName}.app/Contents/Resources/Mindustry.json")

                if(platform != "MacOS"){
                    copy{
                        into "build/packr/output/jre/"
                        from "build/packr/output/desktop.jar"
                    }

                    delete{
                        delete "build/packr/output/desktop.jar"
                    }

                    outputJsonFile.text = outputJsonFile.text.replace("desktop.jar", "jre/desktop.jar")
                }else{
                    copy{
                        into "build/packr/output/${appName}.app/Contents/"
                        from "build/packr/output/Contents/"
                    }

                    delete{
                        delete "build/packr/output/Contents/"
                    }
                }

                //packr is broken and won't let me add one hyphen,so I have to do that myself later
                outputJsonFile.text = outputJsonFile.text.replace("-enable-native-access=ALL-UNNAMED", "--enable-native-access=ALL-UNNAMED")
            }

            if((platform == "Windows64" || platform == "Windows32")){
                copy{
                    from "build/packr/output/jre/bin/msvcr100.dll"
                    into "build/packr/output/"
                    rename("msvcr100.dll", "MSVCR100.dll")
                }
            }

            if(versionModifier.contains("steam")){
                copy{
                    def lib = platform == "MacOS" || platform == "Linux64" ? "lib" : ""
                    from zipTree(platform == "MacOS" ? "build/packr/output/${appName}.app/Contents/Resources/desktop.jar" : "build/packr/output/jre/desktop.jar").matching{
                        include "${lib}steamworks4j${platform == "Windows64" ? '64.dll' : platform == "Windows32" ? '.dll' : platform == "Linux64" ? '.so' : '.dylib'}"
                        include "${lib}steam_api${platform == "Windows64" ? '64.dll' : platform == "Windows32" ? '.dll' : platform == "Linux64" ? '.so' : '.dylib'}"
                    }
                    into platform != "MacOS" ? "build/packr/output/" : "build/packr/output/${appName}.app/Contents/Resources"
                }
            }

            copy{
                from "build/packr/output"
                into "../deploy/${platform.toString()}"
            }
        }

        task "zip${platform.toString()}"(type: Zip){
            from "build/packr/output"
            archiveFileName = "${generateDeployName(platform.toString())}.zip"
            destinationDirectory = (file("../deploy"))

            doLast{
                delete{
                    delete "build/packr/"
                }
            }
        }

        finalizedBy "zip${platform.toString()}"

    }
}
