plugins {
    id 'com.android.application'
    id 'kotlin-android'
    id 'org.jetbrains.kotlin.plugin.compose'
}

// add -Pstrict.release to the gradle command line to enable
if (project.hasProperty('strict.release')) {
    println "Running strict release"
} else {
    apply from: '../config/checkstyle/checkstyle.gradle'
    apply from: '../config/pmd/pmd.gradle'
}

/* gets the version name from the latest Git tag */
def getVersionName = { ->
    def stdout = new ByteArrayOutputStream()
    exec {
        commandLine 'git', 'describe', '--tags', '--always'
        standardOutput = stdout
    }
    return stdout.toString().trim()
}

// yes, this actually needs both quotes https://stackoverflow.com/a/41391841
def privilegedExtensionApplicationId = '"org.fdroid.fdroid.privileged"'

android {
    namespace "org.fdroid.fdroid"
    buildToolsVersion "35.0.0"

    compileSdk libs.versions.compileSdk.get().toInteger()

    defaultConfig {
        versionCode 1023051
        versionName getVersionName()
        applicationId "org.fdroid"

        testInstrumentationRunner 'androidx.test.runner.AndroidJUnitRunner'
        minSdkVersion 23
        targetSdkVersion 31
        /*
          The Android Testing Support Library collects analytics to continuously improve the testing
          experience. More specifically, it uploads a hash of the package name of the application
          under test for each invocation. If you do not wish to upload this data, you can opt-out by
          passing the following argument to the test runner: disableAnalytics "true".
         */
        testInstrumentationRunnerArguments disableAnalytics: 'true'
        vectorDrawables.useSupportLibrary = true
    }

    ext {
        APP_NAME = "@string/app_name"
        APP_NAME_DEBUG = "@string/app_name_debug"
    }

    buildTypes {
        // use proguard on debug too since we have unknowingly broken
        // release builds before.
        all {
            manifestPlaceholders = [applicationLabel: APP_NAME]
            minifyEnabled true
            shrinkResources true
            buildConfigField "String", "PRIVILEGED_EXTENSION_PACKAGE_NAME", privilegedExtensionApplicationId
            buildConfigField "String", "ACRA_REPORT_EMAIL", '"reports@f-droid.org"' // String needs both quotes
            buildConfigField "String", "ACRA_REPORT_FILE_NAME", '"ACRA-report.stacktrace.json"'
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro'
            testProguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro', 'src/androidTest/proguard-rules.pro'
        }
        debug {
            getIsDefault().set(true)
            manifestPlaceholders = [applicationLabel: APP_NAME_DEBUG]
            applicationIdSuffix ".debug"
            versionNameSuffix "-debug"
            // testProguardFiles gets partially ignored for instrumentation tests
            proguardFiles getDefaultProguardFile('proguard-android.txt'), 'proguard-rules.pro', 'src/androidTest/proguard-rules.pro'
            println 'buildTypes.debug defaultConfig.versionCode ' + defaultConfig.versionCode
        }
    }

    flavorDimensions "base"
    productFlavors {
        full {
            getIsDefault().set(true)
            dimension "base"
            applicationIdSuffix ".fdroid"
        }
        basic {
            dimension "base"
            targetSdkVersion 36
            applicationIdSuffix ".basic"
        }
    }
    applicationVariants.all { variant ->
        variant.resValue "string", "applicationId", variant.applicationId
    }

    compileOptions {
        compileOptions.encoding = "UTF-8"
        sourceCompatibility JavaVersion.VERSION_17
        targetCompatibility JavaVersion.VERSION_17
    }

    kotlinOptions {
        jvmTarget = '17'
    }

    aaptOptions {
        cruncherEnabled = false
    }

    buildFeatures {
        buildConfig true
        compose true
        aidl true
    }

    testOptions {
        unitTests {
            includeAndroidResources = true
            // prevent tests from dying on android.util.Log calls
            returnDefaultValues = true
            all {
                // All the usual Gradle options.
                testLogging {
                    events "skipped", "failed", "standardOut", "standardError"
                    showStandardStreams = true
                }
                systemProperty 'robolectric.dependency.repo.url', 'https://repo1.maven.org/maven2'
            }
        }
    }

    sourceSets {
        test {
            java.srcDirs += "$projectDir/src/testShared/java"
        }

        androidTest {
            java.srcDirs += "$projectDir/src/testShared/java"
        }
    }

    lintOptions {
        checkReleaseBuilds false
        abortOnError true

        htmlReport true
        xmlReport false
        textReport false

        lintConfig file("lint.xml")
    }

    /* Do not include files that are not verified by the JAR signature */
    packagingOptions {
        // this can be removed once JAR/APKv1 signatures are no longer supported
        exclude 'META-INF/**/*.properties'
        exclude 'META-INF/*.version'
        exclude 'META-INF/COPYRIGHT'
        exclude 'META-INF/INDEX.LIST'
        exclude 'META-INF/LICENSE'
        exclude 'META-INF/LICENSE.txt'
        exclude 'META-INF/LICENSE.md'
        exclude 'META-INF/LICENSE-notice.md'
        exclude 'META-INF/NOTICE'
        exclude 'META-INF/NOTICE.txt'
        exclude 'META-INF/gradle/**'
        exclude '.readme'
    }
}

dependencies {
    implementation project(":libs:download")
    implementation project(":libs:index")
    implementation project(":libs:database")
    implementation libs.androidx.appcompat
    implementation libs.androidx.preference.ktx
    implementation libs.androidx.gridlayout
    implementation libs.androidx.recyclerview
    implementation libs.androidx.vectordrawable
    implementation libs.androidx.constraintlayout
    implementation libs.androidx.swiperefreshlayout
    implementation libs.androidx.lifecycle.livedata.ktx
    implementation libs.androidx.work.runtime
    implementation libs.guava // somehow needed for work-runtime to function

    implementation libs.material

    //noinspection UseTomlInstead
    implementation('com.journeyapps:zxing-android-embedded:4.3.0') { transitive = false }
    implementation libs.zxing.core
    implementation libs.guardianproject.netcipher
    implementation libs.commons.io
    implementation libs.commons.net
    implementation libs.acra.mail
    implementation libs.acra.dialog
    implementation libs.adapterdelegates4
    implementation libs.slf4j.api
    implementation libs.logback.android
    implementation libs.microutils.kotlin.logging

    implementation libs.rxjava
    implementation libs.rxandroid

    implementation libs.glide
    implementation(libs.glide.compose)
    annotationProcessor libs.glide.compiler

    implementation libs.okhttp
    implementation libs.bcprov.jdk15to18
    fullImplementation libs.guardianproject.panic
    fullImplementation libs.bcpkix.jdk15to18
    fullImplementation libs.jmdns
    fullImplementation libs.nanohttpd

    implementation platform(libs.androidx.compose.bom)
    implementation libs.androidx.compose.material3
    implementation libs.androidx.compose.material.icons.extended
    implementation libs.androidx.lifecycle.viewmodel.compose
    implementation libs.androidx.compose.ui.tooling.preview
    implementation libs.androidx.activity.compose
    implementation libs.accompanist.drawablepainter
    debugImplementation libs.androidx.compose.ui.tooling

    testImplementation libs.androidx.test.core
    testImplementation libs.junit
    testImplementation libs.robolectric
    testImplementation libs.mockk
    testImplementation libs.mockito.core
    testImplementation libs.turbine
    testImplementation libs.hamcrest
    testImplementation libs.slf4j.simple

    androidTestImplementation libs.androidx.test.core
    androidTestImplementation libs.androidx.core.testing
    androidTestImplementation libs.androidx.test.runner
    androidTestImplementation libs.androidx.test.rules
    androidTestImplementation libs.androidx.test.ext.junit
    androidTestImplementation libs.androidx.test.ext.junit.ktx
    androidTestImplementation libs.androidx.test.monitor
    androidTestImplementation libs.androidx.espresso.core
    androidTestImplementation libs.androidx.test.uiautomator
    androidTestImplementation libs.androidx.work.testing
    androidTestImplementation libs.kotlin.test
    androidTestImplementation libs.kotlin.reflect
    androidTestImplementation libs.mockk.android
    androidTestImplementation libs.turbine
}

// org.fdroid.fdroid.updater.UpdateServiceTest needs app-full-debug.apk
android.productFlavors.all { flavor ->
    if (flavor.name == "full") {
        project.afterEvaluate { project ->
            def dep = tasks.getByName("assembleFullDebug")
            project.tasks.withType(Test) { task ->
                task.dependsOn dep
            }
        }
    }
}
