import com.ejt.build.*
import com.install4j.build.*
import java.io.FileInputStream
import java.net.URI
import javax.xml.parsers.DocumentBuilderFactory
import javax.xml.xpath.XPathFactory

plugins {
    `java-library`
}

javaVersion = "11"

dependencies {
    api(project(":install4j:install4j_runtime", "modularizedRuntime"))
    addFlatLaf(coreOnly = true)
}

val helloDist = file("$rootProjectDir/dist/install4j/samples/hello")
val updateFile = File(helloDist, "hello_update.install4j")
val mediaDir = File(helloDist, "media_update")

tasks {

    val createUpdateProject = register<XslConvertTask>("createUpdateProject") {
        mustRunAfter(":install4j:install4j:dist")

        xslFile = project(":install4j:install4j").file("hello_updater.xsl")
        inputFile = project(":install4j:default-dist:install4j:samples:hello").file("hello.install4j")
        outputFile = updateFile
    }

    val buildHelloUpdate = register<JavaExec>("buildHelloUpdate") {
        dependsOn(":install4j:install4j:dist", createUpdateProject)
        doFirstWith(mediaDir, fileSystemOperations) { mediaDir, fsOps ->
            fsOps.delete { delete(mediaDir) }
        }
    }
    provideNotarizationKey(buildHelloUpdate)

    projectsEvaluated(buildHelloUpdate) {
        configureCompilerBase(true)
        args(updateFile)
    }

    val scanHelloUpdate = register<Clamscan>("scanHelloUpdate") {
        dependsOn(buildHelloUpdate)
        workingDir = mediaDir
    }

    register("transferHelloUpdate") {
        dependsOn(scanHelloUpdate)
        val hasKeepHello = project.hasProperty("keepHello")
        val files = fileTreeExclude(mediaDir, "*.txt")
        val targetDir = mediaDir
        doLastWith(files, hasKeepHello, updateFile, fileSystemOperations) {files, hasKeepHello, updateFile, fsOps ->
            val autoUpdateDescriptorUrl = URI(
                XPathFactory.newInstance().newXPath().evaluate(
                    "/install4j/installerGui/@autoUpdateDescriptorUrl",
                    DocumentBuilderFactory.newInstance().newDocumentBuilder().parse(FileInputStream(updateFile)).documentElement
                )
            )
            val remoteDir = File(autoUpdateDescriptorUrl.path).parentFile.path.replace('\\', '/')

            println("Transferring hello update:")
            S3Handler.uploadToDownload(files, remoteDir)
            if (!hasKeepHello) {
                fsOps.delete { delete(targetDir, updateFile) }
            }
        }
    }

    register<RunOnGithub>("transferHelloUpdateGithub")
}

