buildscript {
    repositories {
        mavenLocal()
        mavenCentral()
        gradlePluginPortal()

        maven{ name = "Assimbly Base"
            url = uri("https://maven.pkg.github.com/assimbly/base")
            credentials {
                username = project.findProperty("mavenUser") ?: System.getenv("GITHUB_ACTOR")
                password = project.findProperty("mavenToken") ?: System.getenv("GITHUB_TOKEN")}
        }
        maven{ name = "Assimbly Runtime"
            url = uri("https://maven.pkg.github.com/assimbly/runtime")
            credentials {
                username = project.findProperty("mavenUser") ?: System.getenv("GITHUB_ACTOR")
                password = project.findProperty("mavenToken") ?: System.getenv("GITHUB_TOKEN")}
        }
        maven{  name = "Assimbly Custom Components"
            url = uri("https://maven.pkg.github.com/assimbly/custom-components")
            credentials {
                username = project.findProperty("mavenUser") ?: System.getenv("GITHUB_ACTOR")
                password = project.findProperty("mavenToken") ?: System.getenv("GITHUB_TOKEN")}
        }

    }
}

plugins {
    id "ua.eshepelyuk.ManifestClasspath" version "1.0.0"
    id "application"
    id "java"
    id "java-library"
    id "maven-publish"
    id "idea"
    id "eclipse"
    id "org.springframework.boot"
    id "com.google.cloud.tools.jib"
    id "com.gorylenko.gradle-git-properties"
    id "com.github.node-gradle.node"
    id "org.liquibase.gradle"
    id "io.spring.nohttp"
    id 'de.undercouch.download' version '5.6.0'
    id "com.github.ben-manes.versions" version "0.52.0"
}

group = "org.assimbly.gateway"
version = '5.0.8-SNAPSHOT'
description = "A message gateway"

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

tasks.withType(JavaExec) {
    systemProperty "ASSIMBLY_ENV", System.getProperty("ASSIMBLY_ENV")
}

apply from: "$rootDir/scripts/upgrade/upgrade.gradle"
apply from: "$rootDir/scripts/resources/resources.gradle"
apply from: "$rootDir/scripts/version/version.gradle"
apply from: "gradle/docker.gradle"
apply plugin: 'maven-publish'
apply plugin: 'org.springframework.boot'
apply plugin: 'io.spring.dependency-management'
apply plugin: 'eclipse'

configurations.all {
    exclude group: 'org.slf4j', module: 'slf4j-log4j12'
    exclude group: 'org.jboss.slf4j', module: 'slf4j-jboss-logmanager'
    exclude group: "org.slf4j", module: "slf4j-nop"
    exclude group: "org.slf4j", module: "slf4j-log4j12"
    exclude group: "org.slf4j", module: "slf4j-simple"
    exclude group: "org.apache.logging.log4j", module: 'log4j-slf4j-impl'
    exclude group: 'commons-logging', module: 'commons-logging'
    exclude group: 'xerces', module: 'xercesImpl'
    resolutionStrategy {
        force 'com.fasterxml.jackson.core:jackson-annotations:2.18.2'
        force 'com.fasterxml.jackson.core:jackson-databind:2.18.2'
        force 'com.fasterxml.jackson.dataformat:jackson-dataformat-xml:2.18.2'
        force 'com.fasterxml.jackson.datatype:jackson-datatype-hibernate6:2.18.2'
        force 'com.fasterxml.jackson.datatype:jackson-datatype-hppc:2.18.2'
        force 'com.fasterxml.jackson.datatype:jackson-datatype-jsr310:2.18.2'
        force 'com.fasterxml.jackson.module:jackson-module-afterburner:2.18.2'
        force 'com.fasterxml.jackson.module:jackson-module-jaxb-annotations:2.18.2'
    }
}

idea {
    module {
        excludeDirs += files("node_modules")
    }
}

eclipse {
    sourceSets {
        main {
            java {
                srcDirs += ["build/generated/sources/annotationProcessor/java/main"]
            }
        }
    }
}

// Example images
// image = 'eclipse-temurin:21' (temurin on docker)
// image = 'open-21-jdk-jammy' (semeru on dockerhub)
// image = 'azul/zulu-openjdk:21-jdk-crac-latest' (support for crac)
// image = 'container-registry.oracle.com/graalvm/jdk:21'
// image = 'arm64v8/openjdk:21-jdk-oracle'
//build container image
jib {
    from {
        image = 'container-registry.oracle.com/graalvm/jdk:21'
    }
    to {
        image = 'assimbly/gateway-full'
    }
    container {
        mainClass = 'org.assimbly.gateway.GatewayApp'
        ports = ['1000','1616','1617','2000-2003/udp','8088','8443','9000','9001','27017','61616','61617']
        format = 'OCI'
    }
    containerizingMode = 'exploded'
    extraDirectories {
        paths {
            path {
                // copies the contents of 'src/main/jib' into '/' on the container
                from = file('src/main/jib')
            }
            path {
                // copies the contents of 'src/main/data' into '/data' on the container
                from = file('src/main/data')
                into = '/data'
            }
        }
        permissions = [
            '/entrypoint.sh': '755',
            '/data/**': '775',
            '/data/**/*': '775',
        ]
    }

}

if (project.hasProperty("headless")) {
    apply from: "gradle/profile_headless.gradle"
}else if (project.hasProperty("prod")) {
    apply from: "gradle/profile_prod.gradle"
} else {
    apply from: "gradle/profile_dev.gradle"
}

defaultTasks "bootRun"

springBoot {
    mainClassName = "org.assimbly.gateway.GatewayApp"
}

test {
    useJUnitPlatform()
    exclude "**/*IT*", "**/*IntTest*"

    testLogging {
        events 'FAILED', 'SKIPPED'
    }
    reports.html.required = false
}

task integrationTest(type: Test) {
    useJUnitPlatform()
    description = "Execute integration tests."
    group = "verification"
    include "**/*IT*", "**/*IntTest*"

    testLogging {
        events 'FAILED', 'SKIPPED'
    }
    // uncomment if the tests reports are not generated
    // see https://github.com/jhipster/generator-jhipster/pull/2771 and https://github.com/jhipster/generator-jhipster/pull/4484
    // ignoreFailures true
    reports.html.required = false
}

check.dependsOn integrationTest
task testReport(type: TestReport) {
    destinationDirectory = layout.buildDirectory.dir("reports/tests").get().asFile
    getTestResults()
}

task integrationTestReport(type: TestReport) {
    destinationDirectory = layout.buildDirectory.dir("reports/tests").get().asFile
    getTestResults()
}

if (!project.hasProperty("runList")) {
    project.ext.runList = "main"
}

task getDeps(type: Copy) {
    from sourceSets.main.runtimeClasspath
    into 'runtime/'
}

project.ext.diffChangelogFile = "src/main/resources/config/liquibase/changelog/" + new Date().format("yyyyMMddHHmmss") + "_changelog.xml"

liquibase {
    activities {
        main {
            driver "org.h2.Driver"
            url "jdbc:h2:file:./target/h2db/db/gateway"
            username "gateway"
            password ""
            changeLogFile "src/main/resources/config/liquibase/master.xml"
            defaultSchemaName ""
            logLevel "debug"
            classpath "src/main/resources/"
        }
        diffLog {
            driver "org.h2.Driver"
            url "jdbc:h2:file:./target/h2db/db/gateway"
            username "gateway"
            password ""
            changeLogFile project.ext.diffChangelogFile
            referenceUrl "hibernate:spring:org.assimbly.gateway.domain?dialect=org.hibernate.dialect.H2Dialect&hibernate.physical_naming_strategy=org.springframework.boot.orm.jpa.hibernate.SpringPhysicalNamingStrategy&hibernate.implicit_naming_strategy=org.springframework.boot.orm.jpa.hibernate.SpringImplicitNamingStrategy"
            defaultSchemaName ""
            logLevel "debug"
            classpath layout.buildDirectory.dir("/classes/java/main")
        }
    }

    runList = project.ext.runList
}

gitProperties {
    failOnNoGitDirectory = false
    keys = ["git.branch", "git.commit.id.abbrev", "git.commit.id.describe"]
}

configurations {
    providedRuntime

    liquibaseRuntime.extendsFrom(sourceSets.main.compileClasspath)

    compile { transitive = false }
    all {
        resolutionStrategy {
            eachDependency { DependencyResolveDetails details ->
                if (details.requested.group == 'org.apache.activemq' && details.requested.name.startsWith('artemis') ) {
                    details.useVersion("2.38.0")
                }
                if (details.requested.group == 'org.apache.activemq' && details.requested.name.startsWith('activemq') && !details.requested.name.startsWith('activemq-artemis') && !details.requested.name.startsWith('activemq-branding')) {
                    details.useVersion("6.1.4")
                }
            }
        }
    }
}

repositories {
    mavenLocal()
    mavenCentral()

    maven{  name = "Aurea"
        url "https://int-factory.aurea.com/nexus/content/repositories/sonic-releases/"
    }

    maven{ name = "Assimbly Base"
        url = uri("https://maven.pkg.github.com/assimbly/base")
        credentials {
            username = project.findProperty("mavenUser") ?: System.getenv("GITHUB_ACTOR")
            password = project.findProperty("mavenToken") ?: System.getenv("GITHUB_TOKEN")}
    }
    maven{ name = "Assimbly Runtime"
        url = uri("https://maven.pkg.github.com/assimbly/runtime")
        credentials {
            username = project.findProperty("mavenUser") ?: System.getenv("GITHUB_ACTOR")
            password = project.findProperty("mavenToken") ?: System.getenv("GITHUB_TOKEN")}
    }
    maven{  name = "Assimbly Custom Components"
        url = uri("https://maven.pkg.github.com/assimbly/custom-components")
        credentials {
            username = project.findProperty("mavenUser") ?: System.getenv("GITHUB_ACTOR")
            password = project.findProperty("mavenToken") ?: System.getenv("GITHUB_TOKEN")}
    }

}

dependencies {

    if (project.hasProperty("integration") || project.hasProperty("headless")) {
        implementation group: "org.assimbly", name: "integration-rest", version: "${version}", changing: true
    }else if (project.hasProperty("broker")) {
        implementation group: "org.assimbly", name: "broker-rest", version: "${version}", changing: true
    }else{
        implementation group: "org.assimbly", name: "integration-rest", version: "${version}", changing: true
        implementation group: "org.assimbly", name: "broker-rest", version: "${version}", changing: true
    }

    implementation group:  "org.assimbly", name: "aggregate", version: "${version}", changing: true
    implementation group:  "org.assimbly", name: "amazon", version: "${version}", changing: true
    implementation group:  "org.assimbly", name: "camel-as2-component", version: "${version}", changing: true
    implementation group:  "org.assimbly", name: "csvtoxml", version: "${version}", changing: true
    implementation group:  "org.assimbly", name: "docconverter", version: "${version}", changing: true
    implementation group:  "org.assimbly", name: "edi", version: "${version}", changing: true
    implementation group:  "org.assimbly", name: "edifact", version: "${version}", changing: true
    implementation group:  "org.assimbly", name: "edifactdotweb", version: "${version}", changing: true
    implementation group:  "org.assimbly", name: "edifactstandards", version: "${version}", changing: true
    implementation group:  "org.assimbly", name: "encoder", version: "${version}", changing: true
    implementation group:  "org.assimbly", name: "enrich", version: "${version}", changing: true
    implementation group:  "org.assimbly", name: "exceltoxml", version: "${version}", changing: true
    implementation group:  "org.assimbly", name: "flv", version: "${version}", changing: true
    implementation group:  "org.assimbly", name: "formtoxml", version: "${version}", changing: true
    implementation group:  "org.assimbly", name: "tenantvariables", version: "${version}", changing: true
    implementation group:  "org.assimbly", name: "googledrive", version: "${version}", changing: true
    implementation group:  "org.assimbly", name: "jsontoxmllegacy", version: "${version}", changing: true
    implementation group:  "org.assimbly", name: "oauth2token", version: "${version}", changing: true
    implementation group:  "org.assimbly", name: "oriflame", version: "${version}", changing: true
    implementation group:  "org.assimbly", name: "pdf", version: "${version}", changing: true
    implementation group:  "org.assimbly", name: "pdftotext", version: "${version}", changing: true
    implementation group:  "org.assimbly", name: "replace", version: "${version}", changing: true
    implementation group:  "org.assimbly", name: "sandbox", version: "${version}", changing: true
    implementation group:  "org.assimbly", name: "soap", version: "${version}", changing: true
    implementation group:  "org.assimbly", name: "simplereplace", version: "${version}", changing: true
    implementation group:  "org.assimbly", name: "smb", version: "${version}", changing: true
    implementation group:  "org.assimbly", name: "sql", version: "${version}", changing: true
    implementation group:  "org.assimbly", name: "xmltocsv", version: "${version}", changing: true
    implementation group:  "org.assimbly", name: "xmltoexcel", version: "${version}", changing: true
    implementation group:  "org.assimbly", name: "xmltojsonlegacy", version: "${version}", changing: true

    implementation "com.fasterxml.jackson.core:jackson-annotations:2.18.2"
    implementation "com.fasterxml.jackson.core:jackson-databind:2.18.2"
    implementation "com.fasterxml.jackson.dataformat:jackson-dataformat-xml:2.18.2"
    implementation "com.fasterxml.jackson.datatype:jackson-datatype-hibernate6:2.18.2"
    implementation "com.fasterxml.jackson.datatype:jackson-datatype-hppc:2.18.2"
    implementation "com.fasterxml.jackson.datatype:jackson-datatype-jsr310:2.18.2"
    implementation "com.fasterxml.jackson.module:jackson-module-afterburner:2.18.2"
    implementation "com.fasterxml.jackson.module:jackson-module-jaxb-annotations:2.18.2"
    implementation "com.mattbertolini:liquibase-slf4j:5.1.0"
    implementation "com.mysql:mysql-connector-j"
    implementation "com.warrenstrange:googleauth:1.5.0"
    implementation "commons-io:commons-io"
    implementation "javax.cache:cache-api"
    implementation "net.logstash.logback:logstash-logback-encoder:8.0"
    implementation "org.apache.commons:commons-lang3"
    implementation 'org.eclipse.angus:jakarta.mail'
    implementation "org.ehcache:ehcache"
    implementation "org.hibernate.orm:hibernate-core:${hibernate_version}"
    implementation "org.hibernate.orm:hibernate-envers:${hibernate_version}"
    implementation "org.hibernate.orm:hibernate-jcache:${hibernate_version}"
    implementation "org.hibernate.validator:hibernate-validator:8.0.1.Final"
    implementation "org.liquibase:liquibase-core:${liquibase_version}"
    implementation "org.mapstruct:mapstruct-processor:${mapstruct_version}"
    implementation "org.mapstruct:mapstruct:${mapstruct_version}"
    implementation "org.mongodb:mongodb-driver-core:4.7.2"
    implementation "org.mongodb:mongodb-driver-sync:4.7.2"
    implementation "org.quartz-scheduler:quartz"
    implementation "org.springframework.boot:spring-boot-starter-aop"
    implementation "org.springframework.boot:spring-boot-starter-data-jpa"
    implementation "org.springframework.boot:spring-boot-starter-oauth2-resource-server"
    implementation "org.springframework.boot:spring-boot-starter-thymeleaf"
    implementation "org.springframework.boot:spring-boot-starter-validation"
    implementation "org.springframework.security:spring-security-config"
    implementation "org.springframework.security:spring-security-web"
    implementation "org.springframework:spring-context-support"
    implementation 'io.hawt:hawtio-springboot:4.5.0'
    implementation 'jakarta.persistence:jakarta.persistence-api'
    implementation 'tech.jhipster:jhipster-framework:8.9.0'

    annotationProcessor "org.mapstruct:mapstruct-processor:${mapstruct_version}"
    annotationProcessor "org.hibernate:hibernate-jpamodelgen:${hibernate_version}"
    annotationProcessor ("org.springframework.boot:spring-boot-configuration-processor") {
        exclude group: 'com.vaadin.external.google', module: 'android-json'
    }

    testImplementation "org.springframework.boot:spring-boot-test"
    testImplementation "org.assertj:assertj-core"
    testImplementation "junit:junit"
    testImplementation "org.mockito:mockito-core"
    testImplementation "com.mattbertolini:liquibase-slf4j"

    runtimeOnly "com.h2database:h2:2.3.232"

    liquibaseRuntime "org.liquibase:liquibase-core:${liquibase_version}"
    liquibaseRuntime "org.liquibase.ext:liquibase-hibernate6:${liquibase_version}"
    liquibaseRuntime "com.h2database:h2"
    liquibaseRuntime "com.mysql:mysql-connector-j"

}

//Build different jar based on type of application
if (project.hasProperty("integration")){
    sourceSets {
        main {
            java {
                exclude 'org/assimbly/gateway/config/memory/**'
                exclude 'org/assimbly/gateway/web/rest/headless/**'
                exclude 'org/assimbly/gateway/web/rest/broker/**'
            }
        }
    }
}else if (project.hasProperty("broker")) {
    sourceSets {
        main {
            java {
                exclude 'org/assimbly/gateway/camel/**'
                exclude 'org/assimbly/gateway/config/importing/Import.java'
                exclude 'org/assimbly/gateway/config/memory/**'
                exclude 'org/assimbly/gateway/web/rest/headless/**'
                exclude 'org/assimbly/gateway/web/rest/integration/**'
                exclude 'org/assimbly/gateway/web/rest/gateway/EnvironmentVariablesResource.java'
                exclude 'org/assimbly/gateway/web/rest/gateway/GroupResource.java'
            }
        }
    }
}else if (project.hasProperty("headless")) {
    sourceSets {
        main {
            java {

                exclude 'org/assimbly/gateway/web/rest/broker/**'
                exclude 'org/assimbly/gateway/web/rest/gateway/**'
                exclude 'org/assimbly/gateway/web/rest/integration/**'

                exclude 'org/assimbly/gateway/config/database/**'

                exclude 'org/assimbly/gateway/config/audit/*'
                exclude 'org/assimbly/gateway/config/exporting/*'
                exclude 'org/assimbly/gateway/config/importing/*'
                exclude 'org/assimbly/gateway/config/scheduling/*'

                exclude 'org/assimbly/gateway/domain/*'
                exclude 'org/assimbly/gateway/repository/*'
                exclude 'org/assimbly/gateway/service/*'

                exclude 'org/assimbly/gateway/security/DomainUserDetailsService.java'
                exclude 'org/assimbly/gateway/web/rest/vm/ManagedUserVM.java'
                exclude 'org/assimbly/gateway/web/rest/errors/ExceptionTranslator.java'

            }
        }
    }
}else {
    sourceSets {
        main {
            java {
                exclude 'org/assimbly/gateway/config/memory/**'
                exclude 'org/assimbly/gateway/web/rest/headless/**'
            }
        }
    }
}

publishing {
    publications {
        mavenJava(MavenPublication) {

            if (project.hasProperty("integration")) {
                artifactId = 'integration'
            }else if (project.hasProperty("broker")) {
                artifactId = 'broker'
            }else if (project.hasProperty("headless")) {
                artifactId = 'headless'
            }else{
                artifactId = 'full'
            }

            from components.java
        }
    }
    /*
    repositories {
        maven {
            name = "GitHubPackages"
            url = "https://maven.pkg.github.com/assimbly/gateway"
            credentials {
                username = System.getenv("GITHUB_ACTOR")
                password = System.getenv("GITHUB_TOKEN")
            }
        }
    }

     */
}

tasks.named('bootJar') {
    duplicatesStrategy = DuplicatesStrategy.EXCLUDE
}

task cleanResources(type: Delete) {
    delete "build/resources"
}

tasks.all {
    if (name == 'explodeCodeSourceMain') {
        dependsOn tasks.named('compileJava')
    }
}

task printVersion {
    def versionValue = project.version // Capture at configuration time
    doLast {
        println versionValue
    }
}

//After upgrading execute Gradle wrapper task: ./gradlew wrapper (gradlew.bat wrapper on Windows)
wrapper {
    gradleVersion = "8.12.1"
}

if (project.hasProperty("nodeInstall")) {
    node {
        version = "20.15.1"
        npmVersion = "9.5.1"
        yarnVersion = "1.22.19"
        download = true
    }
}

compileJava.dependsOn processResources
processResources.dependsOn cleanResources,bootBuildInfo
bootBuildInfo.mustRunAfter cleanResources
