/*
 * Copyright 2015-2025 Real Logic Limited, Adaptive Financial Consulting Ltd., Monotonic Ltd.
 *
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 * https://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
plugins {
    alias(libs.plugins.shadow).apply(false)
    alias(libs.plugins.versions)
}

def artioGroup = 'uk.co.real-logic'
def iLink3Enabled = false

defaultTasks 'clean', 'build'

static int getBuildJavaVersion() {
    def buildJavaVersion = System.getenv('BUILD_JAVA_VERSION') ?: JavaVersion.current().getMajorVersion()
    if (buildJavaVersion.indexOf('.') > 0) {
        buildJavaVersion = buildJavaVersion.substring(0, buildJavaVersion.indexOf('.'))
    }
    if (buildJavaVersion.indexOf('-') > 0) {
        buildJavaVersion = buildJavaVersion.substring(0, buildJavaVersion.indexOf('-'))
    }
    Integer.parseInt(buildJavaVersion)
}
int buildJavaVersion = getBuildJavaVersion()

def projectPom = {
    name = 'artio'
    packaging = 'jar'
    description = 'High-Performance FIX Gateway'

    url = 'https://github.com/artiofix/artio'

    scm {
        connection = 'scm:git:https://github.com/artiofix/artio.git'
        developerConnection = 'scm:git:https://github.com/artiofix/artio.git'
        url = 'https://github.com/artiofix/artio.git'
    }

    licenses {
        license {
            name = 'The Apache License, Version 2.0'
            url = 'https://www.apache.org/licenses/LICENSE-2.0.txt'
        }
    }

    developers {
        developer {
            id = 'RichardWarburton'
            name = 'Richard Warburton'
            email = 'richard.warburton@gmail.com'
            url = 'https://github.com/RichardWarburton'
        }
        developer {
            id = 'mjpt777'
            name = 'Martin Thompson'
            email = 'mjpt777@gmail.com'
            url = 'https://github.com/mjpt777'
        }
    }
}

def getConfigProperty(final String projectPropertyName, final String envVarName) {
    String value = project.findProperty(projectPropertyName)
    if (!value) {
        value = System.getenv(envVarName)
        if (!value) {
            return null
        }
    }

    value = value.trim()

    return value ? value : null
}

ext {
    isReleaseVersion = !version.endsWith('-SNAPSHOT')
    iLink3Enabled = Boolean.getBoolean("fix.core.iLink3Enabled")

    sonatypeCentralPortalReleasesRepoUrl = 'https://ossrh-staging-api.central.sonatype.com/service/local/staging/deploy/maven2/'
    sonatypeCentralPortalSnapshotsRepoUrl = 'https://central.sonatype.com/repository/maven-snapshots/'
    sonatypeCentralPortalUsername = getConfigProperty('sonatypeCentralPortalUsername', 'SONATYPE_CENTRAL_PORTAL_USERNAME')
    sonatypeCentralPortalPassword = getConfigProperty('sonatypeCentralPortalPassword', 'SONATYPE_CENTRAL_PORTAL_PASSWORD')

    signingKey = getConfigProperty('signingKey', 'SIGNING_GPG_SECRET_KEY')         // NOTE: ASCII armored secret key
    signingPassword = getConfigProperty('signingPassword', 'SIGNING_GPG_PASSWORD') // NOTE: Plain text
}

allprojects {
    repositories {
        mavenLocal()
        mavenCentral()
    }

    configurations.configureEach {
        resolutionStrategy {
            failOnVersionConflict()

            force libs.agrona,
                    libs.byteBuddy,
                    libs.byteBuddy.agent,
                    // patching conflicting Checkstyle dependencies
                    libs.commons.codec,
                    libs.commons.lang3,
                    libs.httpcore,
                    libs.plexus.utils
        }
    }
}

subprojects {
    apply plugin: 'java-library'
    apply plugin: 'checkstyle'

    group = artioGroup
    version = version

    def toolchainLauncher = javaToolchains.launcherFor {
        languageVersion = JavaLanguageVersion.of(buildJavaVersion)
    }

    java {
        toolchain {
            languageVersion = JavaLanguageVersion.of(buildJavaVersion)
        }
        sourceCompatibility = JavaVersion.VERSION_17
    }

    tasks.withType(JavaCompile).configureEach {
        options.encoding = 'UTF-8'
        options.deprecation = true
    }

    tasks.withType(Sign).configureEach {
        onlyIf {
            isReleaseVersion && gradle.taskGraph.hasTask(tasks.publish)
        }
    }

    dependencies {
        testImplementation libs.hamcrest
        testImplementation libs.mockito
        testImplementation platform(libs.junit.bom)
        testImplementation "org.junit.jupiter:junit-jupiter"
        testRuntimeOnly "org.junit.platform:junit-platform-launcher"
        testRuntimeOnly "org.junit.vintage:junit-vintage-engine"
    }

    checkstyle.toolVersion = libs.versions.checkstyle.get()

    tasks.withType(Test).configureEach {
        useJUnitPlatform()

        jvmArgs('--add-opens', 'java.base/sun.nio.ch=ALL-UNNAMED')
        jvmArgs('--add-opens', 'java.base/jdk.internal.misc=ALL-UNNAMED')
        jvmArgs('--add-opens', 'java.base/java.util.zip=ALL-UNNAMED')

        if (buildJavaVersion >= 21) {
            jvmArgs('-XX:+EnableDynamicAgentLoading')
        }

        testClassesDirs = testing.suites.test.sources.output.classesDirs
        classpath = testing.suites.test.sources.runtimeClasspath
        maxHeapSize = "1g"
        jvmArgs("-XX:MaxDirectMemorySize=1g",
                "-XX:+HeapDumpOnOutOfMemoryError",
                "-XX:+CrashOnOutOfMemoryError",
                "-XX:HeapDumpPath=" + project.rootDir + "/heap.hprof")

        testLogging {
            events 'skipped', 'failed'
            showStandardStreams = true
            exceptionFormat = 'full'
            afterSuite { desc, result ->
                if (!desc.parent) {
                    println "Results: ${result.resultType} (${result.testCount} tests, " +
                            "${result.successfulTestCount} successes, " +
                            "${result.failedTestCount} failures, " +
                            "${result.skippedTestCount} skipped)"
                }
            }
        }

        systemProperties(
            'fix.core.close_checker': 'true',
            'fix.core.debug': System.getProperty("fix.core.debug"),
            'fix.core.ci': System.getProperty("fix.core.ci"),
            'aeron.dir.warn.if.exists': 'false',
            'aeron.use.windows.high.res.timer': 'true',
            'aeron.term.buffer.sparse.file': 'true',
            'aeron.perform.storage.checks': 'false',
            'aeron.publication.unblock.timeout': '35000000000',
            'aeron.client.liveness.timeout': '30000000000')

        def threshold = System.getProperty("org.agrona.transport.iteration.threshold")
        systemProperty "org.agrona.transport.iteration.threshold", threshold

        beforeTest { desc ->
            if (System.properties["printTestNames"] != null) {
                print "Executing test ${desc.name} [${desc.className}]"
            }
        }

        afterTest { desc, result ->
            if (System.properties["printTestNames"] != null) {
                println " with result: ${result.resultType}"
            }
        }

        javaLauncher.set(toolchainLauncher)
    }

    tasks.withType(JavaExec).configureEach {
        javaLauncher.set(toolchainLauncher)
    }

    javadoc {
        title = '<h1>Artio</h1>'
        options.bottom = '<i>Copyright &#169; 2015-2025 Real Logic Limited, Adaptive Financial Consulting Ltd., Monotonic Ltd. All Rights Reserved.</i>'
        options.encoding = 'UTF-8'
        options.docEncoding = 'UTF-8'
        options.charSet = 'UTF-8'
        options.addBooleanOption('html5', true)
        options.addStringOption('Xdoclint:all,-missing', '-quiet')
    }

    jar {
        manifest.attributes(
            'Implementation-Title': 'Artio',
            'Implementation-Version': archiveVersion,
            'Implementation-Vendor': 'Adaptive Financial Consulting'
        )
    }

    tasks.register('testJar', Jar) {
        dependsOn testClasses
        archiveClassifier.set('tests')
        archiveBaseName.set("test-${base.archivesName}")
        from sourceSets.test.output
    }

    tasks.register('allDeps', DependencyReportTask) {}

    configurations {
        tests
    }

    artifacts {
        tests testJar
    }

    java {
        withSourcesJar()
        withJavadocJar()
    }
}

def validationXsdPath = project(':artio-codecs').projectDir.toString() + '/src/main/resources/fpl/sbe.xsd'

project(':artio-codecs') {
    apply plugin: 'com.gradleup.shadow'
    apply plugin: 'maven-publish'
    apply plugin: 'signing'

    configurations {
        codecGeneration
    }

    dependencies {
        api libs.agrona
        api libs.aeron.client
        api libs.sbe
        api files("${layout.buildDirectory.get()}/classes/java/generated")
        codecGeneration libs.sbe
    }

    def generatedDir = file("${layout.buildDirectory.get()}/generated-src")
    sourceSets {
        generated {
            java.srcDir generatedDir
            compileClasspath += configurations.codecGeneration
        }
    }

    compileJava.dependsOn 'compileGeneratedJava'

    compileGeneratedJava.dependsOn 'generateMessages'

    tasks.register('generateMessages', JavaExec) {
        mainClass.set('uk.co.real_logic.sbe.SbeTool')
        jvmArgs('--add-opens', 'java.base/jdk.internal.misc=ALL-UNNAMED')
        classpath = configurations.codecGeneration
        systemProperties('sbe.output.dir': generatedDir,
            'sbe.target.language': 'Java',
            'sbe.validation.stop.on.error': 'true',
            'sbe.validation.xsd': validationXsdPath)
        args = [
                'src/main/resources/uk/co/real_logic/artio/messages/message-schema.xml',
                'src/main/resources/uk/co/real_logic/artio/storage/storage-message-schema.xml'
        ]
    }

    jar {
        from sourceSets.generated.output
    }

    sourcesJar {
        dependsOn 'generateMessages'
        from sourceSets.generated.java
    }

    javadoc {
        source += sourceSets.generated.java
    }

    checkstyleGenerated.enabled = false

    publishing {
        publications {
            artioCodecs(MavenPublication) {
                from components.java
                pom(projectPom)
            }
        }
    }

    signing {
        if (signingKey != null) {
            useInMemoryPgpKeys(signingKey, signingPassword)
        }
        sign publishing.publications.artioCodecs
    }
}

project(':artio-ilink3-codecs') {
    apply plugin: 'com.gradleup.shadow'
    apply plugin: 'maven-publish'
    apply plugin: 'signing'

    configurations {
        codecGeneration
    }

    dependencies {
        api libs.agrona
        api files("${layout.buildDirectory.get()}/classes/java/generated")
        codecGeneration libs.sbe
    }

    def outputClasses = 'out/production/classes'
    def sbePath = 'src/main/resources/uk/co/real_logic/artio/ilink/ilinkbinary.xml'
    def generatedDir = file("${layout.buildDirectory.get()}/generated-src")
    sourceSets {
        generated {
            java.srcDir generatedDir
            compileClasspath += configurations.codecGeneration
        }
    }

    if (iLink3Enabled) {
        compileJava.dependsOn 'compileGeneratedJava'
        compileGeneratedJava.dependsOn 'generateMessages', 'copySbeIr'

        tasks.register('generateMessages', JavaExec) {
            mainClass.set('uk.co.real_logic.sbe.SbeTool')
            jvmArgs('--add-opens', 'java.base/jdk.internal.misc=ALL-UNNAMED')
            classpath = configurations.codecGeneration
            systemProperties(
                'sbe.output.dir': generatedDir,
                'sbe.target.language': 'Java',
                'sbe.java.generate.interfaces': 'true',
                'sbe.generate.ir': 'true')
            args = [sbePath]
        }

        tasks.register('copySbeIr', Copy) {
            dependsOn 'generateMessages'
            from generatedDir.absolutePath + "/ilinkbinary.sbeir"
            into outputClasses + '/iLinkBinary'
        }

        sourcesJar {
            dependsOn generateMessages
            from sourceSets.generated.java
        }

        javadoc {
            dependsOn compileGeneratedJava
            source += sourceSets.generated.java
        }

        jar {
            from sourceSets.generated.output

            from(outputClasses) {
                include 'iLinkBinary/ilinkbinary.sbeir'
            }
        }
    }

    checkstyleGenerated.enabled = false

    publishing {
        publications {
            artioILink3Codecs(MavenPublication) {
                from components.java
                pom(projectPom)
            }
        }
    }

    signing {
        if (signingKey != null) {
            useInMemoryPgpKeys(signingKey, signingPassword)
        }
        sign publishing.publications.artioILink3Codecs
    }
}

project(':artio-binary-entrypoint-codecs') {
    apply plugin: 'com.gradleup.shadow'
    apply plugin: 'maven-publish'
    apply plugin: 'signing'

    configurations {
        codecGeneration
    }

    dependencies {
        api libs.agrona
        api files("${layout.buildDirectory.get()}/classes/java/generated")
        codecGeneration libs.sbe
    }

    def outputClasses = 'out/production/classes'
    def sbePath = 'src/main/resources/uk/co/real_logic/artio/entrypoint/binary_entrypoint.xml'
    def generatedDir = file("${layout.buildDirectory.get()}/generated-src")
    sourceSets {
        generated {
            java.srcDir generatedDir
            compileClasspath += configurations.codecGeneration
        }
    }

    compileJava.dependsOn 'compileGeneratedJava'
    compileGeneratedJava.dependsOn 'generateMessages', 'copySbeIr'

    tasks.register('generateMessages', JavaExec) {
        mainClass.set('uk.co.real_logic.sbe.SbeTool')
        jvmArgs('--add-opens', 'java.base/jdk.internal.misc=ALL-UNNAMED')
        classpath = configurations.codecGeneration
        systemProperties(
            'sbe.output.dir': generatedDir,
            'sbe.target.language': 'Java',
            'sbe.java.generate.interfaces': 'true',
            'sbe.generate.ir': 'true')
        args = [sbePath]
    }

    tasks.register('copySbeIr', Copy) {
        dependsOn 'generateMessages'
        from generatedDir.absolutePath + "/binary_entrypoint.sbeir"
        into outputClasses + '/b3/entrypoint/fixp/sbe/'
    }

    sourcesJar {
        dependsOn 'generateMessages'
        from sourceSets.generated.java
    }

    javadoc {
        source += sourceSets.generated.java
    }

    jar {
        from sourceSets.generated.output

        from(outputClasses) {
            include '/b3/entrypoint/fixp/sbe/binary_entrypoint.sbeir'
        }
    }

    checkstyleGenerated.enabled = false

    publishing {
        publications {
            artioBinaryEntrypointCodecs(MavenPublication) {
                from components.java
                pom(projectPom)
            }
        }
    }

    signing {
        if (signingKey != null) {
            useInMemoryPgpKeys(signingKey, signingPassword)
        }
        sign publishing.publications.artioBinaryEntrypointCodecs
    }
}

project(':artio-binary-entrypoint-impl') {
    apply plugin: 'com.gradleup.shadow'
    apply plugin: 'maven-publish'
    apply plugin: 'signing'

    dependencies {
        api project(':artio-binary-entrypoint-codecs')
        api project(':artio-codecs')
        api project(':artio-core')
    }

    publishing {
        publications {
            artioBinaryEntrypointImpl(MavenPublication) {
                from components.java
                pom(projectPom)
            }
        }
    }

    signing {
        if (signingKey != null) {
            useInMemoryPgpKeys(signingKey, signingPassword)
        }
        sign publishing.publications.artioBinaryEntrypointImpl
    }
}

project(':artio-ilink3-impl') {
    apply plugin: 'com.gradleup.shadow'
    apply plugin: 'maven-publish'
    apply plugin: 'signing'

    dependencies {
        if (iLink3Enabled) {
            api project(':artio-ilink3-codecs')
        }

        api project(':artio-codecs')
        api project(':artio-core')
    }

    compileJava.enabled = iLink3Enabled
    compileTestJava.enabled = iLink3Enabled
    test.enabled = iLink3Enabled
    javadoc.enabled = iLink3Enabled

    publishing {
        publications {
            artioIlink3Impl(MavenPublication) {
                from components.java
                pom(projectPom)
            }
        }
    }

    signing {
        if (signingKey != null) {
            useInMemoryPgpKeys(signingKey, signingPassword)
        }
        sign publishing.publications.artioIlink3Impl
    }
}

project(':artio-session-codecs') {
    apply plugin: 'maven-publish'
    apply plugin: 'signing'

    configurations {
        codecGeneration
    }

    dependencies {
        api project(':artio-codecs')
        api files("${layout.buildDirectory.get()}/classes/java/generated")
        codecGeneration project(':artio-codecs')
    }

    def generatedDir = file("${layout.buildDirectory.get()}/generated-src")
    sourceSets {
        generated {
            java.srcDir generatedDir
            compileClasspath += configurations.codecGeneration
        }
    }

    compileJava.dependsOn 'compileGeneratedJava'
    compileGeneratedJava.dependsOn 'generateCodecs', 'generateOtherCodecs'

    tasks.register('generateCodecs', JavaExec) {
        mainClass.set('uk.co.real_logic.artio.dictionary.CodecGenerationTool')
        jvmArgs('--add-opens', 'java.base/jdk.internal.misc=ALL-UNNAMED')
        classpath = configurations.codecGeneration
        def dictionaryFile = 'src/main/resources/session_dictionary.xml'
        inputs.file(dictionaryFile)
        args = [generatedDir, dictionaryFile]
        outputs.dir generatedDir
        systemProperty("fix.codecs.flyweight", "true")
    }

    tasks.register('generateOtherCodecs', JavaExec) {
        mainClass.set('uk.co.real_logic.artio.dictionary.CodecGenerationTool')
        jvmArgs('--add-opens', 'java.base/jdk.internal.misc=ALL-UNNAMED')
        classpath = configurations.codecGeneration
        def dictionaryFile = 'src/main/resources/other_session_dictionary.xml'
        inputs.file(dictionaryFile)
        args = [generatedDir, dictionaryFile]
        outputs.dir generatedDir
        systemProperty("fix.codecs.flyweight", "true")
        systemProperty("fix.codecs.parent_package", "uk.co.real_logic.artio.other")
    }

    jar {
        from sourceSets.generated.output
    }

    sourcesJar {
        dependsOn 'generateCodecs', 'generateOtherCodecs'
        from sourceSets.generated.java
    }

    javadoc {
        source += sourceSets.generated.java
    }

    publishing {
        publications {
            artioSessionCodecs(MavenPublication) {
                from components.java
                pom(projectPom)
            }
        }
    }

    signing {
        if (signingKey != null) {
            useInMemoryPgpKeys(signingKey, signingPassword)
        }
        sign publishing.publications.artioSessionCodecs
    }
}

project(':artio-session-fixt-codecs') {
    apply plugin: 'maven-publish'
    apply plugin: 'signing'

    configurations {
        codecGeneration
    }

    dependencies {
        api project(path: ':artio-codecs')
        api files("${layout.buildDirectory.get()}/classes/java/generated")
        codecGeneration project(':artio-codecs')
    }

    def generatedDir = file("${layout.buildDirectory.get()}/generated-src")
    sourceSets {
        generated {
            java.srcDir generatedDir
            compileClasspath += configurations.codecGeneration
        }
    }

    compileJava.dependsOn 'compileGeneratedJava'

    compileGeneratedJava {
        dependsOn 'generateCodecs'
        classpath += configurations.codecGeneration
    }

    tasks.register('generateCodecs', JavaExec) {
        mainClass.set('uk.co.real_logic.artio.dictionary.CodecGenerationTool')
        jvmArgs('--add-opens', 'java.base/jdk.internal.misc=ALL-UNNAMED')
        classpath = configurations.codecGeneration
        systemProperty("fix.codecs.parent_package", "uk.co.real_logic.artio.fixt")
        args = [generatedDir, 'src/main/resources/FIXT11.xml']
        outputs.dir generatedDir
    }

    jar {
        from sourceSets.generated.output
    }

    sourcesJar {
        dependsOn 'generateCodecs'
        from sourceSets.generated.java
    }

    javadoc {
        source += sourceSets.generated.java
    }

    publishing {
        publications {
            artioSessionFixtCodecs(MavenPublication) {
                from components.java
                pom(projectPom)
            }
        }
    }

    signing {
        if (signingKey != null) {
            useInMemoryPgpKeys(signingKey, signingPassword)
        }
        sign publishing.publications.artioSessionFixtCodecs
    }
}

project(':artio-core') {
    apply plugin: 'maven-publish'
    apply plugin: 'signing'

    dependencies {
        api project(':artio-codecs')
        api libs.aeron.client
        api libs.aeron.archive
        api libs.hdrHistogram // FIXME: Api?

        testImplementation project(path: ':artio-codecs', configuration: 'tests')
        testImplementation project(':artio-session-codecs')
        testImplementation project(':artio-session-fixt-codecs')
    }

    test {
        systemProperties('java.net.preferIPv4Stack': true)
    }

    publishing {
        publications {
            artioCore(MavenPublication) {
                from components.java
                artifact(testJar)
                pom(projectPom)
            }
        }
    }

    signing {
        if (signingKey != null) {
            useInMemoryPgpKeys(signingKey, signingPassword)
        }
        sign publishing.publications.artioCore
    }
}

project(':artio-system-tests') {
    apply plugin: 'com.gradleup.shadow'
    apply plugin: 'maven-publish'
    apply plugin: 'signing'

    sourceSets {
        perf
    }

    dependencies {
        api project(':artio-session-codecs')
        api project(':artio-session-fixt-codecs')
        api project(path: ':artio-core')

        testImplementation project(path: ':artio-core', configuration: 'tests')
        testImplementation project(path: ':artio-codecs', configuration: 'tests')

        testImplementation project(path: ':artio-session-codecs', configuration: 'tests')
        testImplementation project(path: ':artio-session-fixt-codecs', configuration: 'tests')

        perfImplementation project
        perfImplementation libs.jmh.core
        // For IDEA:
        implementation libs.jmh.core

        annotationProcessor libs.jmh.generator.annprocess
    }

    test {
    }

    tasks.register('benchmarks') {
        dependsOn perfClasses
        shadowJar {
            archiveClassifier.set("benchmarks")

            from sourceSets.main.output
            from sourceSets.perf.output
            from project.configurations.perfRuntimeClasspath

            manifest.attributes('Main-Class': 'org.openjdk.jmh.Main')
        }

        doLast {
            shadowJar
        }
    }

    publishing {
        publications {
            artioSystemTests(MavenPublication) {
                from components.java
                artifact(testJar)
                pom(projectPom)
            }
        }
    }

    signing {
        if (signingKey != null) {
            useInMemoryPgpKeys(signingKey, signingPassword)
        }
        sign publishing.publications.artioSystemTests
    }
}

project(':artio-ilink-system-tests') {
    apply plugin: 'com.gradleup.shadow'
    apply plugin: 'maven-publish'
    apply plugin: 'signing'

    dependencies {
        testImplementation project(path: ':artio-core', configuration: 'tests')
        testImplementation project(path: ':artio-codecs', configuration: 'tests')
        testImplementation project(path: ':artio-system-tests', configuration: 'tests')

        implementation project(':artio-core')
        implementation project(':artio-ilink3-codecs')
        implementation project(':artio-ilink3-impl')
    }

    compileJava.enabled = iLink3Enabled
    compileTestJava.enabled = iLink3Enabled
    javadoc.enabled = iLink3Enabled

    test {
        onlyIf { iLink3Enabled }
    }

    publishing {
        publications {
            artioILink3SystemTests(MavenPublication) {
                from components.java
                pom(projectPom)
            }
        }
    }

    signing {
        if (signingKey != null) {
            useInMemoryPgpKeys(signingKey, signingPassword)
        }
        sign publishing.publications.artioILink3SystemTests
    }
}

project(':artio-binary-entrypoint-system-tests') {
    apply plugin: 'com.gradleup.shadow'
    apply plugin: 'maven-publish'
    apply plugin: 'signing'

    dependencies {
        testImplementation project(path: ':artio-core', configuration: 'tests')
        testImplementation project(path: ':artio-codecs', configuration: 'tests')
        testImplementation project(path: ':artio-system-tests', configuration: 'tests')
        testImplementation project(':artio-binary-entrypoint-codecs')
        testImplementation project(':artio-binary-entrypoint-impl')
        testImplementation project(':artio-session-codecs')

        implementation project(':artio-core')
        implementation project(':artio-binary-entrypoint-codecs')
        implementation project(':artio-binary-entrypoint-impl')
    }

    publishing {
        publications {
            artioBinaryEntrypointSystemTests(MavenPublication) {
                from components.java
                pom(projectPom)
            }
        }
    }

    signing {
        if (signingKey != null) {
            useInMemoryPgpKeys(signingKey, signingPassword)
        }
        sign publishing.publications.artioBinaryEntrypointSystemTests
    }
}

project(':artio-samples') {
    apply plugin: 'com.gradleup.shadow'
    apply plugin: 'maven-publish'
    apply plugin: 'signing'

    dependencies {
        api project(':artio-core')
        api project(':artio-session-codecs')
        api project(':artio-binary-entrypoint-codecs')
        api project(':artio-binary-entrypoint-impl')
    }

    shadowJar {
        archiveFileName = 'samples.jar'
    }

    build.doLast {
        shadowJar
    }

    publishing {
        publications {
            artioSamples(MavenPublication) {
                from components.java
                pom(projectPom)
            }
        }
    }

    signing {
        if (signingKey != null) {
            useInMemoryPgpKeys(signingKey, signingPassword)
        }
        sign publishing.publications.artioSamples
    }
}

subprojects {
    publishing {
        repositories {
            maven {
                url = !isReleaseVersion ? sonatypeCentralPortalSnapshotsRepoUrl : sonatypeCentralPortalReleasesRepoUrl
                credentials {
                    username = sonatypeCentralPortalUsername
                    password = sonatypeCentralPortalPassword
                }
            }
        }
    }
}

tasks.register('copyTestLogs', Copy) {
    from '.'
    include '**/build/test-output/**'
    include '**/*.log'
    include '**/*.tlog'
    include '**/build/reports/tests/**'
    include '**/build/test-results/*/TEST*.xml'
    include 'LICENSE'
    exclude 'build'
    into 'build/test_logs'

    includeEmptyDirs = false
}

def isNonStable = { String version ->
    def stableKeyword = ['RELEASE', 'FINAL', 'GA'].any { it -> version.toUpperCase().contains(it) }
    def regex = /^[0-9,.v-]+(-r)?$/
    return !stableKeyword && !(version ==~ regex)
}

tasks.named('dependencyUpdates').configure {
    // Reject all non stable versions
    rejectVersionIf {
        isNonStable(it.candidate.version)
    }
}

tasks.register('uploadArtifactsToCentralPortal', uk.co.real_logic.artio.build.SonatypeCentralPortalUploadRepositoryTask) {
    portalUsername.set(sonatypeCentralPortalUsername)
    portalPassword.set(sonatypeCentralPortalPassword)
    groupId.set(artioGroup)
    snapshotRelease.set(!isReleaseVersion)
}

wrapper {
    distributionType = 'ALL'
}
