ext.moduleName = 'stroom.proxy.app'

def fatJarName = 'stroom-proxy-app-all.jar'
def releaseBuildDir = "${projectDir}/build/release"
def configDefaultsFile = "${releaseBuildDir}/config/config-defaults.yml"
def configSchemaFile = "${releaseBuildDir}/config/config-schema.yml"
def sendToStroomScriptVersion = 'send-to-stroom-v3.4.0'

apply plugin: 'application'
apply plugin: 'com.gradleup.shadow'

application {
    mainClass = 'stroom.proxy.app.App'
}

dependencies {
    implementation project(':stroom-core-shared')
    implementation project(':stroom-cache:stroom-cache-api')
    implementation project(':stroom-cache:stroom-cache-impl')
    implementation project(':stroom-data:stroom-data-zip')
    implementation project(':stroom-dictionary:stroom-dictionary-api')
//    implementation project(':stroom-dictionary:stroom-dictionary-impl')
    implementation project(':stroom-docref')
    implementation project(':stroom-docstore:stroom-docstore-api')
    implementation project(':stroom-docstore:stroom-docstore-impl')
    implementation project(':stroom-docstore:stroom-docstore-impl-fs')
    implementation project(':stroom-dropwizard-common')
    implementation project(':stroom-event-logging-rs:stroom-event-logging-rs-api')
    implementation project(':stroom-explorer:stroom-collection-api')
    implementation project(':stroom-explorer:stroom-collection-mock')
    implementation project(':stroom-explorer:stroom-explorer-api')
    implementation project(':stroom-explorer:stroom-docrefinfo-api')
    implementation project(':stroom-importexport:stroom-importexport-api')
    implementation project(':stroom-meta:stroom-meta-api')
    implementation project(':stroom-pipeline')
    implementation project(':stroom-proxy:stroom-proxy-remote-api')
    implementation project(':stroom-proxy:stroom-proxy-repo')
    implementation project(':stroom-query:stroom-query-api')
    implementation project(':stroom-receive:stroom-receive-common')
    implementation project(':stroom-security:stroom-security-api')
    implementation project(':stroom-security:stroom-security-common-impl')
    implementation project(':stroom-security:stroom-security-mock')
    implementation project(':stroom-security:stroom-security-openid-api')
    implementation project(':stroom-task:stroom-task-api')
    implementation project(':stroom-task:stroom-task-impl')
    implementation project(':stroom-util')
    implementation project(':stroom-util-shared')

    implementation libs.aws.sqs
    implementation libs.commons.compress
    implementation libs.dropwizard.assets
    implementation libs.dropwizard.core
    implementation libs.dropwizard.client
    implementation libs.dropwizard.jersey
    implementation libs.dropwizard.jetty
    implementation libs.dropwizard.metrics.healthchecks
    implementation libs.dropwizard.servlets
    implementation libs.dropwizard.metrics.core
    implementation libs.dropwizard.metrics.annotation
    implementation libs.dropwizard.configuration
    implementation libs.eventLogging
    implementation libs.guava
    implementation libs.guice
    implementation libs.jackson.annotations
    implementation libs.jackson.core
    implementation libs.jackson.databind
    implementation libs.jakarta.servlet.api
    implementation libs.jakarta.inject
    implementation libs.jetty.server
    implementation libs.jose4j
    implementation libs.kafka.clients
    implementation libs.kryo
    implementation libs.slf4j.api
    implementation libs.swagger.annotations
    implementation libs.vavr

    runtimeOnly libs.jakarta.el

    testImplementation project(':stroom-test-common')

    testImplementation libs.classgraph
    testImplementation libs.data.faker
    testImplementation libs.dropwizard.testing
    testImplementation libs.dropwizard.validation
    testImplementation libs.guice.extension
    testImplementation libs.guice.grapher
    testImplementation libs.jinjava
    testImplementation libs.jmh.core
    testImplementation libs.jmh.generator.annprocess
    testImplementation libs.mbknor.jackson.jsonSchema
    testImplementation libs.wiremock

    testImplementation libs.bundles.common.test.implementation
    testRuntimeOnly libs.bundles.common.test.runtime
}

jar {
    manifest {
        attributes(
                "Implementation-Title": "Stroom Proxy",
                "Implementation-Version": versions.stroom,
                "Main-Class": "stroom.proxy.app.App"
        )
    }
}

shadowJar {
    // We want to run the tests before we build the fat jar.
    dependsOn test

    // Allows us to build fat jars with lots of files
    zip64 = true

    // A transformer to merges files in META-INF/services
    mergeServiceFiles()

    archiveFileName = fatJarName
}

def proxyDockerBuildDir = "${projectDir}/docker/build"
clean {
    delete proxyDockerBuildDir
}

// Generate the confi.yml files for the zip and docker distributions
tasks.register('generateConfigFiles', JavaExec) {
    classpath = sourceSets.test.runtimeClasspath
    mainClass = "stroom.proxy.dist.GenerateProxyDistributionConfig"
}

// Copy all the files needed by the stroom-proxy docker build into stroom-app/proxy-docker/build
tasks.register('copyFilesForProxyDockerBuild') {
    dependsOn shadowJar
    dependsOn generateConfigFiles

    doFirst {
        // Copy the stroom app fat jar
        copy {
            from layout.buildDirectory.dir("libs/${fatJarName}")
            into proxyDockerBuildDir
        }

        // The config.yml will be put in place by generateConfigFiles
    }
}

test {
    maxParallelForks = 1
}


// The gradle application plugin enables the distribution plugin
// which creates .zip/tar archives by default, as does the shadow plugin
// We have our own buildDistribution task so disable the standard ones to avoid confusion
distZip.enabled = false
distTar.enabled = false
shadowDistZip.enabled = false
shadowDistTar.enabled = false

tasks.register('copyJar', Copy) {
    dependsOn shadowJar
    from shadowJar.outputs.files
    into "${releaseBuildDir}/bin"
}

tasks.register('copyCommonSupportingFiles', Copy) {
    from '../../dist'
    // migrate is a stroom only thing
    exclude '**/migrate.sh'
    into releaseBuildDir
}

tasks.register('copySupportingFiles', Copy) {
    dependsOn copyCommonSupportingFiles

    from 'src/main/resources/banner.txt'
    from 'src/dist'
    into releaseBuildDir

    doLast {
        providers.exec {
            // Move the banner.txt into bin where it is expected
            commandLine 'mv', "${releaseBuildDir}/banner.txt", "${releaseBuildDir}/bin/banner.txt"
        }.result.get()
        // This is a sym-link so it seems to go into the zip with +x perms
        // which we don't want
        //providers.exec {
        //  commandLine 'chmod', '644', "${releaseBuildDir}/config/config.yml"
        //}.result.get()
    }
}

// Create an example yaml config file from the compile-time defaults
tasks.register('generateConfigDefaultsYamlFile', JavaExec) {
    classpath = sourceSets.test.runtimeClasspath
    mainClass = 'stroom.proxy.dist.GenerateProxyExpectedYaml'
    args = [configDefaultsFile, configSchemaFile]
}

// Build the release distribution zip for stroom proxy
tasks.register('buildDistribution', Zip) {

    // run all the tasks that produce content for the zip
    dependsOn copyJar
    dependsOn copySupportingFiles
    dependsOn downloadSend
    dependsOn downloadSendArgs
    dependsOn makeSendExecutable
    dependsOn generateConfigFiles
    dependsOn generateConfigDefaultsYamlFile

    from releaseBuildDir
}

tasks.register('Stroom Proxy Node 1', JavaExec) {
    doFirst {
        // We have to alter the existing jvm args rather than set them so that we don't lose debug args added by
        // IJ Idea.
        def jvmArgsCopy = []
        for (arg in jvmArgs) {
            jvmArgsCopy.add(arg)
        }
        //    -DgwtSuperDevMode=true
        //    -Xmx4g
        //    -Devent.logging.validate=true
        //    --add-opens java.base/java.nio=ALL-UNNAMED
        //    --add-opens java.base/sun.nio.ch=ALL-UNNAMED
        //    --add-opens java.base/java.lang=ALL-UNNAMED
        jvmArgsCopy.add("-Xmx4g")
        jvmArgsCopy.add("-Devent.logging.validate=true")
        jvmArgsCopy.add("--add-opens")
        jvmArgsCopy.add("java.base/java.nio=ALL-UNNAMED")
        jvmArgsCopy.add("--add-opens")
        jvmArgsCopy.add("java.base/sun.nio.ch=ALL-UNNAMED")
        jvmArgsCopy.add("--add-opens")
        jvmArgsCopy.add("java.base/java.lang=ALL-UNNAMED")
        jvmArgs = jvmArgsCopy
    }

    group = 'application'
    classpath = sourceSets.main.runtimeClasspath
    mainClass = 'stroom.proxy.app.App'
    workingDir = '../../'
    args = ['server', 'proxy-local.yml']
}

tasks.register('downloadSend', Download) {
    dependsOn copySupportingFiles
    src "https://github.com/gchq/stroom-clients/releases/download/${sendToStroomScriptVersion}/send_to_stroom.sh"
    dest "${releaseBuildDir}/bin/"

    // Github rate limits unless you authenticate so use the special
    // auto generated workflow GITHUB_TOKEN
    //def token = "$System.env.PAT_FOR_PUBLIC_REPOS"
    def token = System.getenv('GITHUB_TOKEN')
    if (token != null && !token.isEmpty()) {
        // Don't log the actual token obvs
        println "Adding auth token for ${src}"
        header 'Authorization', "Bearer $token"
    }
}

tasks.register('downloadSendArgs', Download) {
    dependsOn copySupportingFiles
    src "https://github.com/gchq/stroom-clients/releases/download/${sendToStroomScriptVersion}/send_to_stroom_args.sh"
    dest "${releaseBuildDir}/bin/"

    // Github rate limits unless you authenticate so use the special
    // auto generated workflow GITHUB_TOKEN
    //def token = "$System.env.PAT_FOR_PUBLIC_REPOS"
    def token = System.getenv('GITHUB_TOKEN')
    if (token != null && !token.isEmpty()) {
        // Don't log the actual token obvs
        println "Adding auth token for ${src}"
        header 'Authorization', "Bearer $token"
    }
}

tasks.register('makeSendExecutable') {
    dependsOn downloadSend
    doLast {
        // The args script is sourced so doesn't need execute perms
        providers.exec {
            commandLine 'chmod', '+x', "${releaseBuildDir}/bin/send_to_stroom.sh"
        }.result.get()
    }
}

// Make the build command create the full distribution
tasks.build.dependsOn copyFilesForProxyDockerBuild
tasks.build.dependsOn shadowJar
tasks.build.dependsOn buildDistribution
