import org.apache.tools.ant.filters.ReplaceTokens

plugins {
    id 'java'
    id 'groovy'
    id 'io.quarkus'
}

repositories {
    mavenCentral()
    mavenLocal()
}

dependencies {
    implementation 'io.quarkus:quarkus-container-image-docker'
    implementation enforcedPlatform("${quarkusPlatformGroupId}:${quarkusPlatformArtifactId}:${quarkusPlatformVersion}")
    implementation 'io.quarkiverse.mybatis:quarkus-mybatis:1.0.7'
    implementation 'io.quarkus:quarkus-grpc'
    implementation 'io.quarkus:quarkus-hibernate-orm'
    implementation 'io.quarkus:quarkus-flyway'
    implementation 'io.quarkiverse.mybatis:quarkus-mybatis-plus:1.0.7'
    implementation 'io.quarkus:quarkus-jdbc-postgresql'
    implementation 'io.quarkus:quarkus-arc'
    implementation 'io.quarkus:quarkus-resteasy-reactive'
    implementation 'io.quarkus:quarkus-hibernate-orm-panache'
    implementation 'io.quarkus:quarkus-config-yaml'
    implementation 'commons-io:commons-io:2.+'

    testImplementation 'io.quarkus:quarkus-junit5'

    compileOnly group: 'org.projectlombok', name: 'lombok', version: '1.18.26'

    annotationProcessor group: 'org.projectlombok', name: 'lombok', version: '1.18.26'
    annotationProcessor("io.quarkus:quarkus-panache-common")
}

group 'cz.mendelu'
version '1.0.0-SNAPSHOT'

java {
    sourceCompatibility = JavaVersion.VERSION_17
    targetCompatibility = JavaVersion.VERSION_17
}

configurations {
    developmentOnly
    runtimeClasspath {
        extendsFrom developmentOnly
    }
    compileOnly {
        extendsFrom annotationProcessor
    }
}

test {
    systemProperty "java.util.logging.manager", "org.jboss.logmanager.LogManager"
}

compileJava {
    options.encoding = 'UTF-8'
    options.compilerArgs << '-parameters'
}

compileTestJava {
    options.encoding = 'UTF-8'
}

def getVersion = { projectName ->
    def stdout = new ByteArrayOutputStream()
    def stderr = new ByteArrayOutputStream()
    try {
        exec {
            commandLine 'git', 'describe', '--tags'
            standardOutput = stdout
            errorOutput = stderr
            ignoreExitValue = true
            workingDir "./$projectName"
        }
        def exitValue = execResult.exitValue
        if (exitValue != 0) {
            throw new Exception("Command exited with value: $exitValue")
        }
    } catch (Exception e) {
        println "Command failed with error: ${stderr.toString().trim()}"
        return 'no-tag'
    }
    def describe = stdout.toString().trim()
    return describe.substring(describe.indexOf('_') + 1, describe.length())
}

ext {
    gitVersion = getVersion()
    dockerImageNamespace = 'dnaanalyser'
    dockerRepository = 'sequence'
    dockerImageTag = gitVersion.contains('-')
            ? 'latest'
            : gitVersion
}

tasks.register("exportEnv") {
    doLast {
        File env = new File('.env')
        env.write """DOCKER_NAMESPACE=$dockerImageNamespace
TAG=$dockerImageTag
"""
    }
}

processResources {
    include '**'
    filter ReplaceTokens, tokens: [
            'gitVersion': gitVersion,
            'assemblyDate': Long.toString(System.currentTimeMillis())
    ]
}

task buildNativeImage(type: Exec) {
    description = 'Builds a native image of the Quarkus application'
    group = 'Build'
    // Define the command to execute.
    if (System.getProperty('os.name').toLowerCase(Locale.ROOT).contains('windows')) {
        commandLine "${project.rootDir}\\gradlew.bat", "clean", "build", "-Dquarkus.package.type=native", "-Dquarkus.native.container-build=true", "-Dquarkus.container-image.build=true"
    } else {
        commandLine "${project.rootDir}/gradlew", "clean", "build", "-Dquarkus.package.type=native", "-Dquarkus.native.container-build=true", "-Dquarkus.container-image.build=true"
    }

    doFirst {
        environment "QUARKUS_CONTAINER_IMAGE_GROUP", "${dockerImageNamespace}"
        environment "QUARKUS_CONTAINER_IMAGE_NAME", "${dockerRepository}"
        environment "QUARKUS_CONTAINER_IMAGE_TAG", "${dockerImageTag}"
    }
}

task buildDevImage(type: Exec) {
    description = 'Builds a DEV image of the Quarkus application'
    group = 'Build'

    // Define the command to execute.
    if (System.getProperty('os.name').toLowerCase(Locale.ROOT).contains('windows')) {
        commandLine "${project.rootDir}\\gradlew.bat", "clean", "build", "-Dquarkus.container-image.build=true"
    } else {
        commandLine "${project.rootDir}/gradlew", "clean", "build", "-Dquarkus.container-image.build=true"
    }

    doFirst {
        environment "QUARKUS_CONTAINER_IMAGE_GROUP", "${dockerImageNamespace}"
        environment "QUARKUS_CONTAINER_IMAGE_NAME", "${dockerRepository}"
        environment "QUARKUS_CONTAINER_IMAGE_TAG", "${dockerImageTag}"
    }
}