// SPDX-FileCopyrightText: Copyright 2020-2025 Mark Rotteveel
// SPDX-License-Identifier: LGPL-2.1-or-later
import org.apache.tools.ant.filters.*
import org.asciidoctor.gradle.jvm.AsciidoctorTask

/*
  Gradle build script for Jaybird - Firebird JDBC driver.

  Uploading archives:

  publish -PcredentialsPassphrase=<credentials password>
 */

plugins {
    id 'java-library'
    id 'nu.studer.credentials' version '3.0'
    id 'maven-publish'
    id 'signing'
    id 'org.asciidoctor.jvm.convert' version '4.0.4'
}

defaultTasks 'clean', 'build'

apply from: 'build-properties.gradle'

group = 'org.firebirdsql.jdbc'
version = project.'version.maven'

allprojects {
    tasks.withType(JavaCompile).configureEach {
        options.encoding = 'UTF-8'
    }
    tasks.withType(Test).configureEach {
        systemProperty 'file.encoding', 'UTF-8'
    }
}

base {
    archivesName = project.mavenName
}

java {
    sourceCompatibility = JavaVersion.VERSION_17
    targetCompatibility = JavaVersion.VERSION_17
    withJavadocJar()
    withSourcesJar()
}

dependencies {
    api libs.jspecify

    // Use JUnit Jupiter API for testing.
    testImplementation platform(testLibs.junit.bom)
    testImplementation testLibs.bundles.junit
    testRuntimeOnly testLibs.junit.platform.launcher

    testImplementation testLibs.bundles.hamcrest
    testImplementation testLibs.assertj.core

    testImplementation platform(testLibs.mockito.bom)
    testImplementation testLibs.bundles.mockito

    testImplementation testLibs.awaitility
    // A lot (if not all) tests for jaybird-native are in the main project given dependencies on test infrastructure
    testImplementation project('jaybird-native')
    if (findProperty('test.chacha64') != 'disabled') {
        testRuntimeOnly project('chacha64-plugin')
    }
}

sourceSets {
    main {
        java {
            srcDirs = ['src/main', 'src/extern']
        }
        resources {
            srcDirs = ['src/resources']
        }
    }
    test {
        java {
            srcDirs = ['src/test', 'src/jna-test']
        }
        resources {
            srcDirs = ['src/test_resources']
        }
    }
}

processResources {
    filter ReplaceTokens, tokens: [
            'NAME'         : project.capitalizedName,
            'VERSION'      : project.'version.simple',
            'MAVEN_NAME'   : project.mavenName,
            'VERSION_FULL' : project.'version.maven',
            'VERSION_MAJOR': project.'version.major',
            'VERSION_MINOR': project.'version.minor'
    ]
}

asciidoctorj {
    version = '3.0.0'

    docExtensions file('doc-extension.groovy')
}

tasks.named('asciidoctor', AsciidoctorTask).configure {
    executionMode = OUT_OF_PROCESS
    attributes 'version_simple': project.'version.simple',
            'version_wo_target': "${project.'version.simple'}${project.'version.tag'}",
            'version_tag': project.'version.tag',
            'version_example': "${project.'version.simple'}${project.'version.tag'}",
            'stylesdir': file('src/docs/theme/jaybird-html'),
            'stylesheet': 'firebird.css',
            'docinfo': 'shared',
            'docinfodir': file('src/docs/theme/jaybird-html/docinfo'),
            'revnumber': false
    jvm {
        jvmArgs "--add-opens", "java.base/sun.nio.ch=ALL-UNNAMED", "--add-opens", "java.base/java.io=ALL-UNNAMED"
    }
}

tasks.register('dist', Zip) {
    //dependsOn jar, javadocJar, sourcesJar, asciidoctor
    destinationDirectory = layout.buildDirectory.dir('dist')

    from jar.outputs
    from javadocJar.outputs
    from sourcesJar.outputs
    from(asciidoctor.outputs) {
        include 'release_notes.html'
    }
    from(asciidoctor.outputs) {
        exclude 'release_notes.html'
        into 'docs'
    }
    from(javadoc.outputs) {
        into 'docs/api'
    }
    from('.') {
        include 'CONTRIBUTING.md'
        include 'SECURITY.md'
    }
    from(configurations.runtimeClasspath) {
        into 'lib'
    }
    // NOTE: Inclusion of files from sub-projects is handled in their respective build.gradle files
}

// REUSE-IgnoreStart
jar {
    manifest {
        attributes(
                'Created-By': "${System.getProperty('java.vm.version')} (${System.getProperty('java.vm.vendor')})",
                'Specification-Title': project.'specification.title',
                'Specification-Version': project.'specification.version',
                'Specification-Vendor': project.'specification.vendor',
                'Implementation-Title': project.'implementation.title',
                'Implementation-Url': project.'implementation.url',
                'Implementation-Version': "$project.version (build: variant=$project.mavenName tag=${project.'version.svntag'} date=${project.'build.id'})",
                'Implementation-Vendor': project.'implementation.vendor',
                'Implementation-Vendor-Id': project.'implementation.vendor.id',
                'Bundle-License': 'LGPL-2.1-or-later OR LGPL-2.1-or-later AND BSD-3-Clause',
                'SPDX-License-Identifier': 'LGPL-2.1-or-later OR LGPL-2.1-or-later AND BSD-3-Clause',
                'SPDX-FileCopyrightText': "Copyright 2001-${project.YEAR} Firebird development team and individual contributors"
        )
    }
}
// REUSE-IgnoreEnd

javadoc {
    options.author()
    options.windowTitle = "$project.capitalizedName ${project.'version.maven'} API"
    options.docTitle = "$project.capitalizedName ${project.'version.maven'}"
    options.bottom = "Copyright &copy; 2001-${project.YEAR} Firebird development team and individual contributors. All rights reserved."
    options.addBooleanOption('html5', true)
    options.addBooleanOption('Xdoclint:none', true)
    exclude 'org/firebirdsql/jdbc/oo/**'
}

test {
    println "Running tests for type ${project.'test.gds_type'}"
    // Use junit platform for unit tests
    useJUnitPlatform()

    // Test configuration, defaults specified in gradle.properties (modify through ext, or use -P<prop>=<value>)
    systemProperties(
            'test.user': project.'test.user',
            'test.password': project.'test.password',
            'test.db.dir': project.'test.db.dir',
            'test.db.host': project.'test.db.host',
            'test.db.port': project.'test.db.port',
            'test.db.lc_ctype': project.'test.db.lc_ctype',
            'test.gds_type': project.'test.gds_type',
            'test.use_firebird_autocommit': project.'test.use.firebird.autocommit',
            'jdk.net.useFastTcpLoopback': project.findProperty('jdk.net.useFastTcpLoopback') ?: 'false',
            'test.db_on_docker': project.findProperty('test.dbondocker') ?: 'false',
            'test.enableProtocol': project.'test.enableProtocol'
    )
    if (project.hasProperty('test.jna.library.path')) {
        systemProperty 'jna.library.path', project.'test.jna.library.path'
    } else if (project.'test.gds_type' == 'NATIVE' || project.'test.gds_type' == 'EMBEDDED') {
        println "Running test type ${project.'test.gds_type'} without explicit native library path. " +
                "Specify property 'test.jna.library.path' to point to a Firebird client location (NATIVE) or " +
                "Firebird install (EMBEDDED)."
    }

    doFirst {
        // ensure the 'standard' database directory exists before the test runs
        def standardDbDir = file(layout.buildDirectory.dir("tmp/db"))
        mkdir standardDbDir
        // ensures a Firebird server can create, use and drop databases from this directory
        ant.chmod(dir: standardDbDir, perm: '777')
    }
}

apply from: 'publish.gradle'
