plugins {
    id 'org.sonarqube'
    id 'java-library'
    id 'java-test-fixtures'
    id 'org.jetbrains.kotlin.jvm'
    id 'maven-publish'
    id 'jacoco'
}

/**
 * Return the latest available domain version from git, if git is installed.
 */
def getGitVersion = { ->
    def domainTagPrefix = 'domain-v'
    def stdout = new ByteArrayOutputStream()
    def stderr = new ByteArrayOutputStream()
    try {
        exec {
            commandLine 'git', 'describe', '--tags', '--match', domainTagPrefix + '*'
            standardOutput = stdout
            errorOutput = stderr
            ignoreExitValue true
        }

        def string = stdout.toString().trim()
        def versionMatches = (string =~ /^${domainTagPrefix}([0-9.]+).*$/)[0][1]

        if (versionMatches.isEmpty()) return null
        return versionMatches
    } catch (ignored) {
        return null
    }
}

dependencies {
    api "org.jetbrains.kotlin:kotlin-stdlib-jdk8:$kotlin_version"
    api "org.jetbrains.kotlinx:kotlinx-coroutines-core:$kotlin_coroutines_version"
    api 'com.googlecode.libphonenumber:libphonenumber:8.13.39'
    api 'androidx.annotation:annotation:1.8.0'
    api 'net.sourceforge.streamsupport:streamsupport-flow:1.7.4'

    api 'com.google.protobuf:protobuf-kotlin-lite:3.25.1'

    implementation "org.slf4j:slf4j-api:$slf4j_version"
    // commons-io >2.6 requires android 8
    implementation 'commons-io:commons-io:2.6'
    implementation 'net.i2p.crypto:eddsa:0.3.0'
    implementation "org.jetbrains.kotlinx:kotlinx-coroutines-android:$kotlin_coroutines_version"

    // Note: when updating this version, we need to include the libjnidispatch.so of the same
    // version for each ABI in app/libs/
    // The libjnidispatch.so files can be found in the .jar file:
    // https://github.com/java-native-access/jna/tree/master/dist
    implementation "net.java.dev.jna:jna:5.13.0"

    testImplementation "junit:junit:$junit_version"
    testImplementation 'org.mockito:mockito-core:4.8.1'
    testImplementation "org.powermock:powermock-reflect:2.0.9"
    testImplementation "org.jetbrains.kotlinx:kotlinx-coroutines-test:$kotlin_coroutines_version"
    testImplementation "org.slf4j:slf4j-simple:$slf4j_version"
    testImplementation "org.jetbrains.kotlin:kotlin-test:$kotlin_version"
    testImplementation project(':test-helpers')

    // OkHttp
    api platform('com.squareup.okhttp3:okhttp-bom:4.12.0')
    api 'com.squareup.okhttp3:okhttp'
    api 'com.squareup.okhttp3:logging-interceptor'
}

sourceSets {
    def isProtobufSubrepositoryInitialized = file("./protocol/src/common.proto").exists()
    assert isProtobufSubrepositoryInitialized: "Error: Git protobuf submodule missing. Please run `git submodule update --init`.\n"

    main {
        java.srcDirs += "./build/generated/source/proto/main/java"
        java.srcDirs += "./build/generated/source/proto/main/kotlin"
        java.srcDirs += './build/generated/source/libthreema'
    }
}

test {
    useJUnit()
}

jacocoTestReport {
    reports {
        xml.required = true
        html.required = false
    }
}

sonarqube {
    properties {
        property 'sonar.projectKey', 'android-client'
        property 'sonar.projectName', 'Threema for Android'
        property "sonar.sources", "src/main/"
        property "sonar.exclusions", "src/main/java/ove/crypto/**"
        property "sonar.tests", "src/test/"
        property "sonar.sourceEncoding", "UTF-8"
        property "sonar.verbose", "true"
        property 'sonar.coverage.jacoco.xmlReportPaths', "$projectDir.parentFile.path/build/reports/jacoco/codeCoverageReport/codeCoverageReport.xml"
    }
}

afterEvaluate {
    def bindingsDirectory = '../build/generated/source/libthreema'

    // Define the task to generate libthreema library (only used to generate bindings for it)
    def generateLibthreema = tasks.register("generateLibthreema", Exec) {
        workingDir "${project.projectDir}/libthreema"
        commandLine 'cargo', 'build', '-F', 'uniffi', '-p', 'libthreema', '--release'
    }

    // Define the task to generate the uniffi bindings for libthreema
    def uniffiBindings = tasks.register("generateUniFFIBindings") {
        dependsOn generateLibthreema
        doLast {
            exec {
                // It seems that the uniffi package generates a "*.so" file on linux and a "*.dylib" on mac
                // while using the cargo build command from the gradle task above ("generateLibthreema").
                final String uniffiLibraryFilePathPrefix = "${project.projectDir}/libthreema/target/release/liblibthreema"
                File uniffiLibraryFile = file("${uniffiLibraryFilePathPrefix}.so")
                if (!uniffiLibraryFile.exists()) {
                    uniffiLibraryFile = file("${uniffiLibraryFilePathPrefix}.dylib")
                }
                assert uniffiLibraryFile.exists(): "Error: Missing pre-generated uniffy library file in libthreema/target/*/ directory.\n"

                workingDir "${project.projectDir}/libthreema"
                commandLine 'cargo', 'run', '-p', 'uniffi-bindgen', 'generate', '--library', "${uniffiLibraryFile.path}", '--language', 'kotlin', '--out-dir', "${bindingsDirectory}", '--no-format'
            }
        }
    }

    tasks["compileKotlin"].dependsOn(uniffiBindings)
}


publishing {
    publications {
        library(MavenPublication) {
            from components.java
            version getGitVersion()
        }
    }
    repositories {
        maven {
            url System.getenv("CI_API_V4_URL") + "/projects/" + System.getenv("CI_PROJECT_ID") + "/packages/maven"
            name "Gitlab"
            credentials(HttpHeaderCredentials) {
                name = 'Job-Token'
                value = System.getenv("CI_JOB_TOKEN")
            }
            authentication {
                header(HttpHeaderAuthentication)
            }
        }
    }
}

tasks.register('compileProto', Exec) {
    workingDir "${project.projectDir}"
    commandLine './compile-proto.sh'
}
tasks.compileKotlin.dependsOn(compileProto)

tasks.register('libthreemaCleanUp', Exec) {
    workingDir "${project.projectDir}/libthreema"
    commandLine 'cargo', 'clean'
}

tasks.clean.dependsOn(libthreemaCleanUp)

java.targetCompatibility = JavaVersion.VERSION_11
sourceCompatibility = JavaVersion.VERSION_11
