apply plugin: "com.android.application"
apply plugin: "org.jetbrains.kotlin.android"
apply plugin: "com.facebook.react"
apply plugin: "io.sentry.android.gradle"

def sentryReactNativePath = ["node", "--print", "require('path').dirname(require.resolve('@sentry/react-native/package.json'))"].execute(null, rootDir).text.trim()

project.ext.sentryCli = [
    collectModulesScript: "${sentryReactNativePath}/dist/js/tools/collectModules.js",
    modulesPaths: ["node_modules"],
    skipCollectModules: false,
    copyDebugIdScript: "${sentryReactNativePath}/scripts/copy-debugid.js",
    hasSourceMapDebugIdScript: "${sentryReactNativePath}/scripts/has-sourcemap-debugid.js",
]

apply from: new File("${sentryReactNativePath}", "sentry.gradle")

sentry {
    // 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 = shouldSentryAutoUpload()

    // 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 = shouldSentryAutoUpload()

    // 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 = true

    // Generates a JVM (Java, Kotlin, etc.) source bundle and uploads your source code to Sentry.
    // This enables source context, allowing you to see your source
    // code as part of your stack traces in Sentry.
    //
    // Default is disabled.
    includeSourceContext = shouldSentryAutoUpload()

    // Includes additional source directories into the source bundle.
    // These directories are resolved relative to the project directory
    // which is /android/app in this sample application.
    // additionalSourceDirsForSourceContext = ["src/main/java"]

    // `@sentry/react-native` ships with compatible `sentry-android`
    // This option would install the latest version that ships with the SDK or SAGP (Sentry Android Gradle Plugin)
    // which might be incompatible with the React Native SDK
    // Enable auto-installation of Sentry components (sentry-android SDK and okhttp, timber and fragment integrations).
    // Default is enabled.
    autoInstallation {
      enabled = false
    }
}

react {
    /* Folders */
    //   The root of your project, i.e. where "package.json" lives. Default is '..'
    // root = file("../")
    //   The folder where the react-native NPM package is. Default is ../node_modules/react-native
    // reactNativeDir = file("../node_modules/react-native")
    //   The folder where the react-native Codegen package is. Default is ../node_modules/@react-native/codegen
    // codegenDir = file("../node_modules/@react-native/codegen")
    //   The cli.js file which is the React Native CLI entrypoint. Default is ../node_modules/react-native/cli.js
    // cliFile = file("../node_modules/react-native/cli.js")
    /* Variants */
    //   The list of variants to that are debuggable. For those we're going to
    //   skip the bundling of the JS bundle and the assets. By default is just 'debug'.
    //   If you add flavors like lite, prod, etc. you'll have to list your debuggableVariants.
    // debuggableVariants = ["liteDebug", "prodDebug"]
    /* Bundling */
    //   A list containing the node command and its flags. Default is just 'node'.
    // nodeExecutableAndArgs = ["node"]
    //
    //   The command to run when bundling. By default is 'bundle'
    // bundleCommand = "ram-bundle"
    //
    //   The path to the CLI configuration file. Default is empty.
    // bundleConfig = file(../rn-cli.config.js)
    //
    //   The name of the generated asset file containing your JS bundle
    // bundleAssetName = "MyApplication.android.bundle"
    //
    //   The entry file for bundle generation. Default is 'index.android.js' or 'index.js'
    // entryFile = file("../js/MyApplication.android.js")
    //
    //   A list of extra flags to pass to the 'bundle' commands.
    //   See https://github.com/react-native-community/cli/blob/main/docs/commands.md#bundle
    // extraPackagerArgs = []
    /* Hermes Commands */
    //   The hermes compiler command to run. By default it is 'hermesc'
    // hermesCommand = "$rootDir/my-custom-hermesc/bin/hermesc"
    //
    //   The list of flags to pass to the Hermes compiler. By default is "-O", "-output-source-map"
    // hermesFlags = ["-O", "-output-source-map"]

    /* Autolinking */
    autolinkLibrariesWithApp()
}

/**
 * Set this to true to Run Proguard on Release builds to minify the Java bytecode.
 */
def enableProguardInReleaseBuilds = true

/**
 * The preferred build flavor of JavaScriptCore.
 *
 * For example, to use the international variant, you can use:
 * `def jscFlavor = io.github.react-native-community:jsc-android-intl:2026004.+`
 *
 * The international variant includes ICU i18n library and necessary data
 * allowing to use e.g. `Date.toLocaleString` and `String.localeCompare` that
 * give correct results when using with locales other than en-US. Note that
 * this variant is about 6MiB larger per architecture than default.
 */
def jscFlavor = 'io.github.react-native-community:jsc-android:2026004.+'

android {
    ndkVersion rootProject.ext.ndkVersion

    buildToolsVersion rootProject.ext.buildToolsVersion
    compileSdkVersion rootProject.ext.compileSdkVersion

    namespace "io.sentry.reactnative.sample"
    defaultConfig {
        applicationId "io.sentry.reactnative.sample"
        minSdkVersion rootProject.ext.minSdkVersion
        targetSdkVersion rootProject.ext.targetSdkVersion
        versionCode 63
        versionName "7.3.0"
    }

    signingConfigs {
        debug {
            storeFile file('debug.keystore')
            storePassword 'android'
            keyAlias 'androiddebugkey'
            keyPassword 'android'
        }
    }

    if (System.getenv('SENTRY_SAMPLE_ENABLE_ABI_SPLIT') == 'true') {
      splits {
          abi {
              enable true
              reset()
              include 'x86', 'arm64-v8a'
              universalApk true
          }
      }
      project.ext.versionCodes = ['armeabi': 1, 'armeabi-v7a': 2, 'arm64-v8a': 3, 'mips': 5, 'mips64': 6, 'x86': 8, 'x86_64': 9]
      android.applicationVariants.all { variant ->
          variant.outputs.each { output ->
              output.versionCodeOverride =
                  project.ext.versionCodes.get(output.getFilter(
                      com.android.build.OutputFile.ABI), 0) * 10000000 + android.defaultConfig.versionCode
          }
      }
    }

    if (System.getenv('SENTRY_SAMPLE_ENABLE_FLAVORS') == 'true') {
      flavorDimensions "version"
      productFlavors {
        regular {
            dimension "version"
        }
        demo {
            dimension "version"
            applicationIdSuffix "demo"
        }
      }
    }

    buildTypes {
        debug {
            signingConfig signingConfigs.debug
        }
        release {
            debuggable true
            // Caution! In production, you need to generate your own keystore file.
            // see https://reactnative.dev/docs/signed-apk-android.
            signingConfig signingConfigs.debug
            minifyEnabled enableProguardInReleaseBuilds
            proguardFiles getDefaultProguardFile("proguard-android.txt"), "proguard-rules.pro"
        }
    }
}

dependencies {
    // The version of react-native is set by the React Native Gradle Plugin
    implementation("com.facebook.react:react-android")

    if (hermesEnabled.toBoolean()) {
        implementation("com.facebook.react:hermes-android")
    } else {
        implementation jscFlavor
    }
}

if (newArchEnabled.toBoolean()) {
  android {
      externalNativeBuild {
        cmake {
            path "src/main/jni/CMakeLists.txt"
        }
    }
  }
}
