plugins {
    id "java"
    id "maven-publish"

    id "com.github.johnrengelman.shadow"
}

description = "gRPC: Netty Shaded"

sourceSets { testShadow {} }

dependencies {
    implementation project(':grpc-netty')
    runtimeOnly libraries.netty_tcnative,
            libraries.netty_epoll
    testShadowImplementation files(shadowJar),
            project(':grpc-testing-proto'),
            project(':grpc-testing'),
            libraries.truth
    shadow project(':grpc-core')
}

jar {
    // Must use a different classifier to avoid conflicting with shadowJar
    classifier = 'original'
}

shadowJar {
    classifier = null
    dependencies {
        include(project(':grpc-netty'))
        include(dependency('io.netty:'))
    }
    relocate 'io.grpc.netty', 'io.grpc.netty.shaded.io.grpc.netty'
    relocate 'io.netty', 'io.grpc.netty.shaded.io.netty'
    // We have to be careful with these replacements as they must not match any
    // string in NativeLibraryLoader, else they cause corruption. Note that
    // this includes concatenation of string literals and constants.
    relocate 'META-INF/native/libnetty', 'META-INF/native/libio_grpc_netty_shaded_netty'
    relocate 'META-INF/native/netty', 'META-INF/native/io_grpc_netty_shaded_netty'
    mergeServiceFiles()
}

publishing {
    publications {
        maven(MavenPublication) {
            // Ideally swap to project.shadow.component(it) when it isn't broken for project deps
            artifact shadowJar
            // Empty jars are not published via withJavadocJar() and withSourcesJar()
            artifact javadocJar
            artifact sourcesJar

            pom.withXml {
                def dependencies = asNode().appendNode('dependencies')
                project.configurations.shadow.allDependencies.each { dep ->
                    def dependencyNode = dependencies.appendNode('dependency')
                    dependencyNode.appendNode('groupId', dep.group)
                    dependencyNode.appendNode('artifactId', dep.name)
                    def version = (dep.name == 'grpc-core') ? '[' + dep.version + ']' : dep.version
                    dependencyNode.appendNode('version', version)
                    dependencyNode.appendNode('scope', 'compile')
                }
            }
        }
    }
}

task testShadow(type: Test) {
    testClassesDirs = sourceSets.testShadow.output.classesDirs
    classpath = sourceSets.testShadow.runtimeClasspath
}
compileTestShadowJava.options.compilerArgs = compileTestJava.options.compilerArgs
compileTestShadowJava.options.encoding = compileTestJava.options.encoding

test.dependsOn testShadow
