/*
 * Copyright (c) 2023  airsquared
 *
 * This file is part of blobsaver.
 *
 * blobsaver is free software: you can redistribute it and/or modify
 * it under the terms of the GNU General Public License as published by
 * the Free Software Foundation, version 3 of the License.
 *
 * blobsaver is distributed in the hope that it will be useful,
 * but WITHOUT ANY WARRANTY; without even the implied warranty of
 * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
 * GNU General Public License for more details.
 *
 * You should have received a copy of the GNU General Public License
 * along with blobsaver.  If not, see <https://www.gnu.org/licenses/>.
 */

import org.apache.tools.ant.filters.ReplaceTokens
import org.gradle.nativeplatform.platform.internal.DefaultNativePlatform

plugins {
    id 'application'
    id 'com.github.ben-manes.versions' version '0.52.0'
    id 'org.beryx.jlink' version '3.1.1'
    id 'org.openjfx.javafxplugin' version '0.1.0'

    id 'idea'
}
idea.module.outputDir file('out/production/classes') // fix running via IntelliJ

/*
 * REMEMBER: also update the version string in Main.java
 */
version = '3.6.0'
description = 'A cross-platform GUI and CLI app for saving SHSH blobs'
String appIdentifier = 'airsquared.blobsaver.app'
String copyright = 'Copyright (c) 2025 airsquared'
var os = DefaultNativePlatform.currentOperatingSystem

startScripts.enabled = distZip.enabled = distTar.enabled = false

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

repositories {
    mavenCentral()
}

dependencies {
    implementation 'com.google.code.gson:gson:2.13.1'
    implementation ('de.jangassen:nsmenufx:3.1.0') {
        exclude group: 'net.java.dev.jna', module: 'jna' //different jna version
    }
    implementation 'net.java.dev.jna:jna-jpms:5.17.0'
    implementation 'org.apache.commons:commons-compress:1.27.1'
    implementation 'info.picocli:picocli:4.7.7'

    testImplementation 'org.junit.jupiter:junit-jupiter:5.13.4'
    testRuntimeOnly 'org.junit.platform:junit-platform-launcher'
    testImplementation 'org.testfx:openjfx-monocle:21.0.2'
}

javafx {
    version = '21.0.8'
    modules = [ 'javafx.controls', 'javafx.fxml' ]
}

var addJvmArgs = ['--enable-preview', '--add-exports=javafx.graphics/com.sun.javafx.css=airsquared.blobsaver']

tasks.withType(JavaCompile).forEach {
    it.options.compilerArgs.addAll addJvmArgs
}

application {
    mainModule = 'airsquared.blobsaver'
    mainClass = 'airsquared.blobsaver.app.Main'
    applicationDefaultJvmArgs.addAll addJvmArgs
}

var jarDirectory = os.isMacOsX() ? 'macos/Contents' : os.isWindows() ? 'windows/files' : 'linux'
jarDirectory =  "${projectDir}/dist/${jarDirectory}"

run {
    systemProperty 'jar.directory', jarDirectory
}

test {
    useJUnitPlatform()
    systemProperty 'jar.directory', jarDirectory
    jvmArgs '--enable-preview'
}

jlink {
    if (findProperty('noCompress') != 'true') {
        addOptions '--strip-debug', '--compress=2', '--no-header-files', '--no-man-pages', '--strip-native-commands',
                '--dedup-legal-notices=error-if-not-same-content'
    }
    launcher {
        jvmArgs = addJvmArgs + '-Djar.directory={{BIN_DIR}}'
        if (findProperty('noConsole') != 'false') {
            noConsole = true
        }
    }
    jpackage {
        imageOptions = [ '--copyright', copyright, '--description', description]
        installerOptions.addAll '--about-url', 'https://github.com/airsquared/blobsaver'
        vendor = 'airsquared'
        installerOutputDir = file(layout.buildDirectory.dir('distributions'))

        if (os.isMacOsX()) {
            installerType = 'dmg'
            var arch = DefaultNativePlatform.currentArchitecture.amd64 ? 'intel' : 'arm'
            installerName = "${name}-${arch}"
            //noinspection GroovyAssignabilityCheck
            imageOptions.addAll '--mac-package-identifier', appIdentifier,
                    '--app-content', file('dist/macos/Contents').listFiles().join(',')
            icon = 'dist/macos/blob.icns'
        } else if (os.isWindows()) {
            icon = 'dist/windows/blob.ico'
            imageOptions.addAll '--app-content', file('dist/windows/files').listFiles().join(',')
        } else {
            installerOptions.addAll '--linux-shortcut', '--linux-menu-group', 'Utility;Archiving;Java',
                    '--linux-rpm-license-type', 'GPLv3'
            icon = 'src/main/resources/airsquared/blobsaver/app/blob.png'
            imageOptions.addAll '--app-content', file('dist/linux').listFiles().join(',')
        }
        if (findProperty('installerType') != null) {
            installerType = findProperty('installerType')
        }
    }
}

task createZip(type: Zip, dependsOn: jpackageImage) {
    if (os.isMacOsX()) {
        String arch = DefaultNativePlatform.currentArchitecture.amd64 ? 'intel' : 'arm'
        archiveFileName = "${project.name}-${arch}-${project.version}.zip"
    } else {
        archiveFileName = "${project.name}-${project.version}.zip"
    }
    from layout.buildDirectory.dir('jpackage')
    destinationDirectory = layout.buildDirectory.dir('distributions')
}

task createTgz(type: Tar, dependsOn: jpackageImage) {
    if (os.isMacOsX()) {
        String arch = DefaultNativePlatform.currentArchitecture.amd64 ? 'intel' : 'arm'
        archiveFileName = "${project.name}-${arch}-${project.version}.tgz"
    } else {
        archiveFileName = "${project.name}-${project.version}.tgz"
    }
    compression = Compression.GZIP
    from layout.buildDirectory.dir('jpackage')
    destinationDirectory = layout.buildDirectory.dir('distributions')
}

task windowsInstaller(type: Exec, dependsOn: jpackageImage) { // requires inno setup to be installed
    doFirst {
        copy {
            from 'dist/windows/blob.ico' into layout.buildDirectory.dir('jpackage')
        }
        copy {
            from 'dist/windows/blobsaver.iss' into layout.buildDirectory.dir('jpackage')
            filter(ReplaceTokens, tokens: [Name: project.name, Version: version, Copyright: copyright,
                                           OutputDir: layout.buildDirectory.dir('distributions').get().toString()])
        }
    }
    commandLine 'iscc', '/Qp', "${layout.buildDirectory.get()}\\jpackage\\blobsaver.iss"
    doLast {
        delete layout.buildDirectory.dir('jpackage/blobsaver.iss')
    }
}

task bumpCaskPR(type: Exec) { // TODO: make into a github workflow
    commandLine "${projectDir}/dist/macos/bump-cask-pr.bash", version
}

if (!os.isWindows()) { // never do jpackage on windows
    assemble.dependsOn jpackage // will be disabled on other OS if installerType is set to certain values
}
if (findProperty('installerType') == 'tar.gz' || findProperty('installerType') == 'tgz') {
    jpackage.enabled = false
    assemble.dependsOn createTgz
}
if (findProperty('installerType') == 'zip') {
    jpackage.enabled = false
    assemble.dependsOn createZip
}
if (findProperty('installerType') == 'portable') {
    jpackage.enabled = false
}
if (os.isLinux() && findProperty('installerType') == null) {
    jpackage.finalizedBy createTgz
}
if (os.isWindows() && findProperty('installerType') == null) {
    assemble.dependsOn windowsInstaller
}

if (hasProperty('buildScan')) {
    buildScan {
        termsOfServiceUrl = 'https://gradle.com/terms-of-service'
        termsOfServiceAgree = 'yes'
    }
}
