apply from: "$rootDir/gradle/gradle_scripts/javafx.gradle"
apply from: "$rootDir/gradle/gradle_scripts/jna.gradle"

def distDir = "${project.layout.buildDirectory.get()}/dist"

// To remove warnings, the plugin probably does not expect the JPackage tasks to be in a separate project
application {
    mainModule = packageName(null)
    mainClass = packageName('Main')
}

def extModules = project.allExtensions
def extLibrariesTasks = extModules.stream().map { it.getTasksByName('createExtOutput', true)[0] }.toList()

dependencies {
    implementation project(':app')
    if (!useBundledJavaFx) {
        configurations.javafx.getAsFileTree().getFiles().forEach {
            implementation files(it)
        }
    }
    if (!useBundledJna) {
        configurations.jna.getAsFileTree().getFiles().forEach {
            implementation files(it)
        }
    }
}

// Mac does not like a zero major version
def macVersion = canonicalVersionString
if (Integer.parseInt(macVersion.substring(0, 1)) == 0) {
    macVersion = "1" + macVersion.substring(1)
}

jlink {
    imageDir = file("${project.layout.buildDirectory.get()}/image")
    options = [
            // Disable this as this removes line numbers from stack traces!
            // '--strip-debug',
            '--no-header-files',
            '--no-man-pages',
            '--compress', 'zip-9',
            '--ignore-signing-information'
    ]

    if (os.isLinux()) {
        options.addAll('--strip-native-debug-symbols', 'exclude-debuginfo-files')
    }

    if (customJavaFxJmodsPath != null) {
        addExtraModulePath(customJavaFxJmodsPath.toString())
    } else if (useBundledJavaFx && !bundledJdkJavaFx) {
        addExtraModulePath(layout.projectDirectory.dir("javafx/${platformName}/${arch}").toString())
    }

    if (useBundledJna) {
        addExtraModulePath(layout.projectDirectory.dir("jna/${platformName}/${arch}").toString())
    }

    for (def extProject : extModules) {
        def dir = "${extProject.buildDir}/libs_ext"
        addExtraModulePath(dir)
        addOptions("--add-modules", groupName + ".ext.${extProject.name}")
    }

    if (!ci || (!isStage && !isFullRelease)) {
        addOptions("--add-modules", "jdk.jdwp.agent")
    }

    launcher {
        moduleName = packageName(null)
        mainClass = packageName('Main')
        name = jpackageExecutableName
        jvmArgs = jpackageReleaseArguments
    }

    jpackage {
        imageOutputDir = file("$distDir/jpackage")
        imageName = jpackageExecutableName
        if (os.isWindows()) {
            icon = "$rootDir/dist/logo/logo.ico"
            appVersion = os.isWindows() ? windowsSchemaCanonicalVersion : canonicalVersionString
        } else if (os.isLinux()) {
            icon = "$rootDir/dist/logo/logo.png"
            appVersion = canonicalVersionString
        } else {
            icon = "$rootDir/dist/logo/logo.icns"
            resourceDir = file("${project.layout.buildDirectory.get()}/macos_resources")
            appVersion = macVersion
        }
        vendor = publisher
        skipInstaller = true
    }
}

tasks.named('jlink').get().dependsOn(rootProject.getTasksByName("jar", true))
tasks.named('jlink').get().dependsOn(extLibrariesTasks)

def outputName = os.isMacOsX() ? "${jpackageExecutableName}.app/Contents/Resources" : jpackageExecutableName
tasks.register('copyBundledExtensions', DefaultTask) {
    dependsOn extLibrariesTasks
    doLast {
        for (def extProject : extModules) {
            def dir = "${extProject.buildDir}/libs_ext"
            if (file(dir).exists()) {
                copy {
                    from(dir)
                    into "$distDir/jpackage/$outputName/extensions/${extProject.name}"
                    include '*.jar'
                }
            }
        }
    }
}

tasks.register('prepareMacOSResources', DefaultTask) {
    doLast {
        file("${project.layout.buildDirectory.get()}/macos_resources").mkdirs()
        copy {
            from replaceVariablesInFile("$projectDir/jpackage/Info.plist",
                                        Map.of('__NAME__',
                                               productName,
                                               '__VERSION__',
                                               versionString,
                                               '__BUNDLE__',
                                               jpackageMacOsBundleName))
            into file("${project.layout.buildDirectory.get()}/macos_resources")
        }
    }
}

tasks.register('finalizeMacOSResources', DefaultTask) {
    doLast {
        copy {
            from file("$projectDir/logo/Assets.car")
            into file("$distDir/jpackage/$outputName")
        }

        file("$distDir/jpackage/$outputName/${jpackageExecutableName}.icns").renameTo(file("$distDir/jpackage/$outputName/xpipe.icns"))
    }
}

if (os.isMacOsX()) {
    jpackageImage.finalizedBy(finalizeMacOSResources)
    jpackageImage.dependsOn(prepareMacOSResources)
}

tasks.jpackage.finalizedBy(copyBundledExtensions)
