plugins {
    // Gradle doesn't allow conditionally enabling/disabling plugins
    id "io.sentry.android.gradle" version "3.3.0"
    id 'com.android.application'
    id 'com.mikepenz.aboutlibraries.plugin'
}

android {
    namespace "com.fox2code.mmm"
    compileSdk 33
    buildToolsVersion '33.0.0'
    signingConfigs {
        release {
            // Everything comes from local.properties
            Properties properties = new Properties()
            if (project.rootProject.file('local.properties').exists()) {
                properties.load(project.rootProject.file('local.properties').newDataInputStream())
                storeFile file(properties.getProperty('keystore.file'))
                storePassword properties.getProperty('keystore.password')
                keyAlias 'key0'
                keyPassword properties.getProperty('keystore.password')
            }
        }
    }

    defaultConfig {
        applicationId "com.fox2code.mmm"
        minSdk 23
        targetSdk 33
        versionCode 61
        versionName "1.0.1"
        testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
        signingConfig signingConfigs.release
    }

    splits {

        // Configures multiple APKs based on ABI.
        abi {

            // Enables building multiple APKs per ABI.
            enable true

            // By default all ABIs are included, so use reset() and include to specify that we only
            // want APKs for x86 and x86_64.

            // Resets the list of ABIs that Gradle should create APKs for to none.
            reset()

            // Specifies a list of ABIs that Gradle should create APKs for.
            include "x86", "x86_64", "armeabi-v7a", "arm64-v8a"

            // Specifies that we do not want to also generate a universal APK that includes all ABIs.
            universalApk true
        }
    }

    buildTypes {
        release {
            minifyEnabled true
            shrinkResources true
            proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'),
                    'proguard-rules.pro'
        }
        debug {
            applicationIdSuffix '.debug'
            debuggable true

            // ONLY FOR TESTING SENTRY
            // minifyEnabled true
            // shrinkResources true
            // proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'),'proguard-rules.pro'
        }
    }

    flavorDimensions "type"
    productFlavors {
        "default" {
            dimension "type"
            buildConfigField "boolean", "ENABLE_AUTO_UPDATER", "true"
            buildConfigField "boolean", "DEFAULT_ENABLE_CRASH_REPORTING", "true"
            if (hasSentryConfig) {
                Properties properties = new Properties()
                try (FileInputStream fis = new FileInputStream(sentryConfigFile)) {
                    properties.load(fis)
                }
                buildConfigField "String", "SENTRY_TOKEN", '"' + properties.getProperty("auth." + "token") + '"'
            } else {

                buildConfigField "String", "SENTRY_TOKEN", '""'

            }
            // Get the androidacy client ID from the androidacy.properties
            Properties properties = new Properties()
            // If androidacy.properties doesn't exist, use the default client ID which is heavily
            // rate limited to 30 requests per minute
            if (project.rootProject.file('androidacy.properties').exists()) {
                properties.load(project.rootProject.file('androidacy.properties').newDataInputStream())
            } else {
                properties.setProperty('client_id', '"5KYccdYxWB2RxMq5FTbkWisXi2dS6yFN9R7RVlFCG98FRdz6Mf5ojY2fyJCUlXJZ"')
            }
            buildConfigField("String", "ANDROIDACY_CLIENT_ID", properties.getProperty('client_id'))
            // If client ID is empty, disable androidacy
            if (properties.getProperty('client_id').isEmpty()) {
                buildConfigField("java.util.List<String>",
                        "ENABLED_REPOS", "java.util.Arrays.asList(\"magisk_alt_repo\")")
            } else {
                buildConfigField("java.util.List<String>",
                        "ENABLED_REPOS",
                        "java.util.Arrays.asList(\"magisk_alt_repo\", \"androidacy_repo\")",)
            }

        }

        fdroid {
            dimension "type"
            applicationIdSuffix ".fdroid"

            // Need to disable auto-updater for F-Droid flavor because their inclusion policy
            // forbids downloading blobs from third-party websites (and F-Droid APK isn't signed
            // with our keys, so the APK wouldn't install anyways).
            buildConfigField "boolean", "ENABLE_AUTO_UPDATER", "false"

            // Disable crash reporting for F-Droid flavor by default
            buildConfigField "boolean", "DEFAULT_ENABLE_CRASH_REPORTING", "false"

            if (hasSentryConfig) {
                Properties properties = new Properties()
                try (FileInputStream fis = new FileInputStream(sentryConfigFile)) {
                    properties.load(fis)
                }
                buildConfigField "String", "SENTRY_TOKEN", '"' + properties.getProperty("auth." + "token") + '"'
            } else {
                buildConfigField "String", "SENTRY_TOKEN", '""'
            }

            // Repo with ads or tracking feature are disabled by default for the
            // F-Droid flavor.
            buildConfigField("java.util.List<String>",
                    "ENABLED_REPOS",
                    "java.util.Arrays.asList(\"magisk_alt_repo\")",)

            // Get the androidacy client ID from the androidacy.properties
            Properties properties = new Properties()
            // If androidacy.properties doesn't exist, use the fdroid client ID which is limited
            // to 50 requests per minute
            if (project.rootProject.file('androidacy.properties').exists()) {
                properties.load(project.rootProject.file('androidacy.properties').newDataInputStream())
            } else {
                properties.setProperty('client_id', '"dQ1p7X8bF14PVJ7wAU6ORVjPB2IeTinsuAZ8Uos6tQiyUdUyIjSyZSmN54QBbaTy"')
            }
            buildConfigField("String", "ANDROIDACY_CLIENT_ID", properties.getProperty('client_id'))
        }
    }

    compileOptions {
        sourceCompatibility JavaVersion.VERSION_11
        targetCompatibility JavaVersion.VERSION_11
    }
    lint {
        disable 'MissingTranslation'
        disable 'TypographyEllipsis'
    }
}

aboutLibraries {
    additionalLicenses = ["LGPL_3_0_only", "Apache_2_0"]
}

// "true" is not allowed inside this block, use "hasSentryConfig" instead.
// This is because gradle doesn't allow to enable/disable plugins conditionally
sentry {
    // Disable sentry on F-Droid flavor
    ignoredFlavors = []

    // Disables or enables the handling of Proguard mapping for Sentry.
    // If enabled the plugin will generate a UUID and will take care of
    // uploading the mapping to Sentry. If disabled, all the logic
    // related to proguard mapping will be excluded.
    // Default is enabled.
    includeProguardMapping = hasSentryConfig

    // Whether the plugin should attempt to auto-upload the mapping file to Sentry or not.
    // If disabled the plugin will run a dry-run and just generate a UUID.
    // The mapping file has to be uploaded manually via sentry-cli in this case.
    // Default is enabled.
    autoUploadProguardMapping = hasSentryConfig

    // Experimental flag to turn on support for GuardSquare's tools integration (Dexguard and External Proguard).
    // If enabled, the plugin will try to consume and upload the mapping file produced by Dexguard and External Proguard.
    // Default is disabled.
    experimentalGuardsquareSupport = hasSentryConfig

    // Disables or enables the automatic configuration of Native Symbols
    // for Sentry. This executes sentry-cli automatically so
    // you don't need to do it manually.
    // Default is disabled.
    uploadNativeSymbols = hasSentryConfig

    // Does or doesn't include the source code of native code for Sentry.
    // This executes sentry-cli with the --include-sources param. automatically so
    // you don't need to do it manually.
    // Default is disabled.
    includeNativeSources = hasSentryConfig

    // Enable or disable the tracing instrumentation.
    // Does auto instrumentation for specified features through bytecode manipulation.
    // Default is enabled.
    tracingInstrumentation {
        enabled = true
    }

    // Enable auto-installation of Sentry components (sentry-android SDK and okhttp, timber and fragment integrations).
    // Default is enabled.
    // Only available v3.1.0 and above.
    autoInstallation {
        enabled = true

        // Specifies a version of the sentry-android SDK and fragment, timber and okhttp integrations.
        //
        // This is also useful, when you have the sentry-android SDK already included into a transitive dependency/module and want to
        // align integration versions with it (if it's a direct dependency, the version will be inferred).
        //
        // NOTE: if you have a higher version of the sentry-android SDK or integrations on the classpath, this setting will have no effect
        // as Gradle will resolve it to the latest version.
        //
        // Defaults to the latest published sentry version.
        sentryVersion = '6.9.2'
    }
}

configurations {
    implementation.exclude group: 'org.jetbrains', module: 'annotations'
}

dependencies {
    // UI
    implementation 'androidx.appcompat:appcompat:1.5.1'
    implementation 'androidx.emoji2:emoji2:1.2.0'
    implementation 'androidx.emoji2:emoji2-views-helper:1.2.0'
    implementation 'androidx.preference:preference:1.2.0'
    implementation 'androidx.constraintlayout:constraintlayout:2.1.4'
    implementation 'androidx.recyclerview:recyclerview:1.2.1'
    implementation 'androidx.swiperefreshlayout:swiperefreshlayout:1.1.0'
    implementation 'androidx.webkit:webkit:1.5.0'
    implementation 'com.google.android.material:material:1.7.0'
    implementation "dev.rikka.rikkax.layoutinflater:layoutinflater:1.2.0"
    implementation "dev.rikka.rikkax.insets:insets:1.3.0"
    implementation 'com.github.Dimezis:BlurView:version-2.0.2'
    implementation 'com.github.KieronQuinn:MonetCompat:0.4.1'
    implementation 'com.github.Fox2Code:FoxCompat:0.1.6'
    // Update the version code in the root build.gradle
    implementation "com.mikepenz:aboutlibraries:${latestAboutLibsRelease}"

    // Utils
    implementation 'androidx.work:work-runtime:2.7.1'
    implementation 'com.squareup.okhttp3:okhttp-dnsoverhttps:5.0.0-alpha.10'
    implementation 'com.squareup.okhttp3:okhttp-brotli:5.0.0-alpha.10'
    // Chromium cronet from androidacy
    implementation 'com.androidacy:cronet-common:108.0.5359.95'
    implementation 'com.androidacy:cronet-native:108.0.5359.95'
    // Force prefer our own version of Cronet
    implementation 'com.github.topjohnwu.libsu:io:5.0.1'
    implementation 'com.github.Fox2Code:RosettaX:1.0.9'
    implementation 'com.github.Fox2Code:AndroidANSI:1.0.1'
    implementation 'io.sentry:sentry-android:6.9.2'

    // Markdown
    implementation "io.noties.markwon:core:4.6.2"
    implementation "io.noties.markwon:html:4.6.2"
    implementation "io.noties.markwon:image:4.6.2"
    implementation "io.noties.markwon:syntax-highlight:4.6.2"
    implementation 'com.google.net.cronet:cronet-okhttp:0.1.0'
    annotationProcessor "io.noties:prism4j-bundler:2.0.0"
    implementation "com.caverock:androidsvg:1.4"
    // Icons
    // implementation "com.mikepenz:iconics-core:3.2.5"
    //implementation "androidx.appcompat:appcompat:${versions.appCompat}"

    // implementation 'com.mikepenz:community-material-typeface:7.0.96.0-kotlin@aar'
    // Test
    testImplementation 'junit:junit:4.13.2'
    androidTestImplementation 'androidx.test.ext:junit:1.1.4'

    // Add okhttp logging interceptor if debug build
    debugImplementation 'com.squareup.okhttp3:logging-interceptor:5.0.0-alpha.10'
}

if (hasSentryConfig) {
    Properties properties = new Properties()
    try (FileInputStream fis = new FileInputStream(sentryConfigFile)) {
        properties.load(fis)
    }
    tasks.withType(Exec) {
        environment "SENTRY_PROJECT", properties.getProperty("defaults.project")
        environment "SENTRY_ORG", properties.getProperty("defaults.org")
        environment "SENTRY_URL", properties.getProperty("defaults.url")
        environment "SENTRY_AUTH_TOKEN", properties.getProperty("auth.token")
    }
}

final String sentrySrc = hasSentryConfig ? 'src/sentry/java' : 'src/sentryless/java'
final String sentryManifestSrc = hasSentryConfig ? 'src/sentry/AndroidManifest.xml' : 'src/sentryless/AndroidManifest.xml'

android {
    sourceSets {
        main {
            java.srcDirs += sentrySrc
            // manifest.srcFile += sentryManifestSrc // Not supported
        }

        // Workaround useless gradle restriction
        "default" {
            manifest.srcFile sentryManifestSrc
        }

        fdroid {
            manifest.srcFile sentryManifestSrc
        }
    }
}
