/*
 * (C) Copyright IBM Deutschland GmbH 2021
 * (C) Copyright IBM Corp. 2021
 */

buildscript {
    ext.kotlin_version = '1.8.20'
}

plugins {
    id 'com.android.application' version '7.4.2' apply false
    id 'org.jetbrains.kotlin.android' version "$kotlin_version" apply false
    id 'org.jetbrains.kotlin.plugin.serialization' version "$kotlin_version" apply false
    id 'io.gitlab.arturbosch.detekt' version '1.18.1' apply false
    id 'com.jaredsburrows.license' version '0.8.90' apply false
    id 'pl.allegro.tech.build.axion-release' version '1.13.3'
    id 'com.github.ben-manes.versions' version '0.39.0'
}

apply from: "$rootDir/gradle/common/repos.gradle"
setupRepos()
apply from: "$rootDir/gradle/common/dependency-updates.gradle"

apply from: "$rootDir/gradle/common/scm-version.gradle"
setupScmVersion()

// FIXME: Change this when we switch to Maven Central or GitHub Packages finally works without authentication
group = 'com.ibm.health.de.rki.covpass'
subprojects {
    group = rootProject.group
    version = rootProject.version

    def isLibraryProject = project.name != 'app' && !project.name.startsWith('app-')
    def isAndroidProject = project.file('src/main/AndroidManifest.xml').exists()
    def isPlatformProject = project.name.endsWith('-bom')
    def isTestProject = project.name.endsWith('-test') || project.name == 'test'
    def shouldPublish = isLibraryProject && project.name.startsWith("covpass-")
    def isThirdPartyProject = project.name == "covpass-dgc-certlogic"
    def kotlinExplicitApiMode = !isThirdPartyProject
    def compilerArgs = [
        "-Xopt-in=de.rki.covpass.sdk.utils.ExperimentalHCertApi",
    ]

    apply from: "$rootDir/dependencies.gradle"

    repositories {
        maven {
            url 'https://maven.pkg.github.com/ehn-dcc-development/*'
            credentials {
                username repoConfig.githubUsername ?: System.getenv("GITHUB_PACKAGES_USERNAME")
                password repoConfig.githubPassword ?: System.getenv("GITHUB_PACKAGES_PASSWORD")
            }
        }
    }

    if (!isPlatformProject) {
        if (!isLibraryProject) {
            apply from: "$rootDir/gradle/common/android-app.gradle"
            androidApp(
                kotlinCompilerArgs: compilerArgs,
                kotlinExplicitApiMode: kotlinExplicitApiMode,
                obfuscation: Obfuscation.Full,
                disableAndroidLints: ["UnusedResources"],
            )
            apply plugin: 'com.jaredsburrows.license'

            licenseReport {
                generateCsvReport = false
                generateHtmlReport = false
                generateJsonReport = true
            }
        } else if (isAndroidProject) {
            apply from: "$rootDir/gradle/common/android-library.gradle"
            androidLibrary(
                kotlinCompilerArgs: compilerArgs,
                kotlinExplicitApiMode: kotlinExplicitApiMode,
            )
        } else {
            apply from: "$rootDir/gradle/common/kotlin-library.gradle"
            kotlinLibrary(
                kotlinCompilerArgs: compilerArgs,
                kotlinExplicitApiMode: kotlinExplicitApiMode,
            )
        }

        if (!isThirdPartyProject) {
            apply from: "$rootDir/gradle/common/ktlint.gradle"
            apply from: "$rootDir/gradle/common/detekt.gradle"
        }

        if (isAndroidProject) {
            android {
                defaultConfig {
                    versionName = "1.44.0"
                }
                if (!isLibraryProject) {
                    def codeName = project.name.substring("app-".length()).replaceAll("-", "")
                    applicationVariants.all { variant ->
                        variant.outputs.all {
                            outputFileName = "$codeName-${defaultConfig.versionName}-${version}-${variant.buildType.name}.apk"
                        }
                    }
                }

                buildFeatures {
                    viewBinding true
                }

                // Resolve build conflicts for test modules
                if (isTestProject) {
                    packagingOptions {
                        pickFirst 'META-INF/AL2.0'
                        pickFirst 'META-INF/LGPL2.1'
                    }
                }

                if (isTestProject || isThirdPartyProject) {
                    lintOptions {
                        abortOnError false
                    }
                }
                // for local release builds and debugging proguard
                def debugKeystore = file("$rootDir/debug.keystore")
                if (debugKeystore.exists()) {
                    signingConfigs {
                        debug {
                            storeFile debugKeystore
                            storePassword 'android'
                            keyAlias 'androiddebugkey'
                            keyPassword 'android'
                        }
                    }
                    buildTypes {
                        debug {
                            signingConfig signingConfigs.debug
                        }
                        release {
                            signingConfig signingConfigs.debug
                        }
                    }
                }
            }

            dependencies {
                baseAndroid()
            }
        } else {
            dependencies {
                base()
            }
        }

        task verifyAll(group: 'verification') {
            if (!isThirdPartyProject) {
                dependsOn 'ktlint'
                dependsOn 'detekt'
            }
            if (isAndroidProject) {
                dependsOn 'lintDebug'
                dependsOn 'testDebugUnitTest'
            } else {
                dependsOn 'test'
            }
        }

        if (isLibraryProject) {
            apply from: "$rootDir/gradle/common/coverage.gradle"
            trackCoverage(enableTestCoverage: isOnCI, trackUI: false)
        }
        if (!isLibraryProject && (System.getenv("PUBLISH_APPS") ?: "true") == "true") {
            apply plugin: 'maven-publish'
            afterEvaluate {
                publishing {
                    publications {
                        release(MavenPublication) {
                            from components.release_apk
                        }
                        debug(MavenPublication) {
                            from components.debug_apk
                            artifactId "${project.name}--debug"
                        }
                    }
                    repositories {
                        maven {
                            url "https://nexus.open-insurance-platform.com/repository/covpass-releases"
                            credentials {
                                username repoConfig.nexusUsername
                                password repoConfig.nexusPassword
                            }
                        }
                    }
                }
            }
        }
    }

    if (shouldPublish) {
        apply from: "$rootDir/gradle/common/publish.gradle"
        publish(
            url: System.getenv("PUBLICATION_URL") ?: nexus.egaPublic,
            username: repoConfig.nexusUsername ?: System.getenv("PUBLICATION_USERNAME"),
            password: repoConfig.nexusPassword ?: System.getenv("PUBLICATION_PASSWORD"),
            repoUrl: "https://github.com/Digitaler-Impfnachweis/covpass-android",
            pomAction: {
                description = "The official CovPass(-Check) SDK"
                url = "https://github.com/Digitaler-Impfnachweis/covpass-android"
                licenses {
                    license(LICENSE.APACHE2)
                }
            },
            isPlatformProject: isPlatformProject,
        )
    }
}
