plugins {
    id 'java-library'
    id "io.freefair.lombok" version "5.3.0"
    id 'com.github.johnrengelman.shadow' version '6.1.0'
    id 'maven-publish'
    id 'signing'
    id 'org.owasp.dependencycheck' version '7.1.0.1'
}


sourceCompatibility = 1.8

repositories {
    mavenCentral()
}

java {
    withSourcesJar()
    withJavadocJar()
}

import java.nio.file.Paths

def readVersion() {
    def versionPropsFile = file(Paths.get("src","main","resources","version.properties"))
    if (versionPropsFile.canRead()) {
        Properties versionProps = new Properties()

        if (versionPropsFile.canRead()) {
            InputStream inputStream = new FileInputStream(versionPropsFile)
            versionProps.load(inputStream)
            inputStream.close()
        }
        versionProps['version']
    } else {
        throw new GradleException("Could not read version.properties!")
    }
}

version = readVersion()
group "software.amazon.msk"

dependencies {
    compileOnly('org.apache.kafka:kafka-clients:2.8.1')
    // aws sdk imports.
    implementation(platform('software.amazon.awssdk:bom:2.32.26'))
    implementation('software.amazon.awssdk:auth')
    implementation('software.amazon.awssdk:sso')
    implementation('software.amazon.awssdk:ssooidc')
    implementation('software.amazon.awssdk:sts')
    implementation('com.fasterxml.jackson.core:jackson-databind:2.18.3')
    implementation('org.slf4j:slf4j-api:1.7.25')

    runtimeOnly('software.amazon.awssdk:apache-client')

    //test dependencies
    testImplementation('org.apache.kafka:kafka-clients:2.2.1')
    testImplementation('org.junit.jupiter:junit-jupiter-api:5.7.0')
    testImplementation('org.apache.commons:commons-lang3:3.11')
    testImplementation('org.mockito:mockito-inline:3.6.0')

    testRuntimeOnly('org.junit.jupiter:junit-jupiter-engine:5.7.0')
    testRuntimeOnly('org.apache.logging.log4j:log4j-core:2.17.1')
    testRuntimeOnly('org.apache.logging.log4j:log4j-slf4j-impl:2.17.1')
}

import com.github.jengelman.gradle.plugins.shadow.tasks.ConfigureShadowRelocation

shadowJar {
    //We remove org.slf4j from the configuration as it gets included transitively by multiple dependencies and just
    //removing it from the configuration being shadowed is not sufficient.
    configurations = [project.configurations.runtimeClasspath.exclude([group: "org.slf4j", module: "slf4j-api"])]
    exclude 'META-INF/versions/17/', 'META-INF/versions/21/', 'META-INF/versions/22/'
}


import java.util.jar.JarFile

class FilteredConfigureShadowRelocation extends ConfigureShadowRelocation {

    @Input
    Set<String> relocationFilterPrefix

    @TaskAction
    void configureRelocation() {
        def packages = [] as Set<String>
        configurations.each { configuration ->
            configuration.files.each { jar ->
                JarFile jf = new JarFile(jar)
                jf.entries().each { entry ->
                    if (entry.name.endsWith(".class")) {
                        packages << entry.name[0..entry.name.lastIndexOf('/')-1].replaceAll('/', '.')
                    }
                }
                jf.close()
            }
        }
        packages.each { pkg ->
            def shouldRelocate = true
            relocationFilterPrefix.each { prefix ->
                if (pkg.startsWith(prefix)) {
                    shouldRelocate = false
                }
            }
            if (shouldRelocate) {
                target.relocate(pkg, "${prefix}.${pkg}")
            }
        }

    }
}

task relocateShadowJar(type: FilteredConfigureShadowRelocation) {
    target = tasks.shadowJar
    prefix = "aws_msk_iam_auth_shadow"
    relocationFilterPrefix = ["org.slf4j", "software.amazon.awssdk"]
}

tasks.shadowJar.dependsOn tasks.relocateShadowJar

test {
    useJUnitPlatform {
        excludeTags 'ignored'
    }
}

publishing {
    publications {
        mavenJava(MavenPublication) {
            from components.java

            pom {
                name = "Amazon MSK Library for AWS Identity and Access Management"
                packaging = "jar"
                url = "https://docs.aws.amazon.com/msk/latest/developerguide/iam-access-control.html"
                description = "The Amazon MSK Library for AWS Identity and Access Management allows JVM based Apache " +
                        "Kafka clients to use AWS IAM for authentication and authorization against Amazon MSK " +
                        "clusters that have AWS IAM enabled as an authentication mechanism"
                scm {
                    url = "https://github.com/aws/aws-msk-iam-auth"
                    connection = "scm:git:https://github.com/aws/aws-msk-iam-auth.git"
                    developerConnection = "scm:git:git@github.com:aws/aws-msk-iam-auth.git"
                }
                licenses {
                    license {
                        name = "The Apache License, Version 2.0"
                        url = "http://www.apache.org/licenses/LICENSE-2.0.txt"
                    }
                }
                developers {
                    developer {
                        id = "amazonwebservices"
                        organization = "Amazon Web Services"
                        organizationUrl = "https://aws.amazon.com"
                    }
                }
            }
        }
    }

    repositories {
        maven {
            name = "sonatype-staging"
            url "https://aws.oss.sonatype.org/service/local/staging/deploy/maven2"
            credentials {
                username project.hasProperty('ossrhUsername') ? project.property('ossrhUsername') : ""
                password project.hasProperty('ossrhPassword') ? project.property('ossrhPassword') : ""
            }
        }
    }

}
signing {
    def signingKey = project.hasProperty('signingKey') ? project.property('signingKey') : ""
    def signingPassword = project.hasProperty('signingPassword') ? project.property('signingPassword') : ""
    useInMemoryPgpKeys(signingKey, signingPassword)
    sign publishing.publications.mavenJava
}
