// Gradle script for generating serialized public app config (from app.config.js/ts or app.json) and bundling it into the APK

import org.apache.tools.ant.taskdefs.condition.Os


def expoConstantsDir = project.providers.exec {
  workingDir(projectDir)
  commandLine("node", "-e", "console.log(require('path').dirname(require.resolve('expo-constants/package.json')));")
}.standardOutput.asText.get().trim()

def config = project.hasProperty("react") ? project.react : [];
def nodeExecutableAndArgs = config.nodeExecutableAndArgs ?: ["node"]

afterEvaluate {
  def expoGradleExtension = gradle.extensions.findByName("expoGradle")
  def customProjectRoot = expoGradleExtension?.projectRoot
  def projectRoot = file("${customProjectRoot ?: rootProject.projectDir}")

  project.android.libraryVariants.all { variant ->
    def assetsDir = file("$buildDir/generated/assets/expo-constants/${variant.name}")
    def configMode = variant.buildType.name == "debug" || variant.buildType.name == "debugOptimized" ? "development" : "production"

    def createConfigTask = tasks.register("create${variant.name.capitalize()}ExpoConfig", Exec) {
      description = 'expo-constants: Create app.config.'

      doFirst {
        assetsDir.deleteDir()
        assetsDir.mkdirs()
      }

      // Mark the task as always out-of-date so it always runs - ie. regenerate app.config on every build
      outputs.upToDateWhen { false }

      // Set up outputs so gradle can cache the result
      outputs.dir assetsDir

      // Switch to project root and generate the app config
      workingDir projectRoot

      // The `false` argument turns the fingerprint embed off here: the task below owns it.
      if (Os.isFamily(Os.FAMILY_WINDOWS)) {
        commandLine("cmd", "/c", *nodeExecutableAndArgs, "$expoConstantsDir/scripts/getAppConfig.js", projectRoot, assetsDir, "android", "false", configMode)
      } else {
        commandLine(*nodeExecutableAndArgs, "$expoConstantsDir/scripts/getAppConfig.js", projectRoot, assetsDir, "android", "false", configMode)
      }
    }

    // Generate app.config at preBuild
    variant.preBuildProvider.configure { it.dependsOn(createConfigTask) }

    // Add generated assetsDir into assets.srcDirs
    project.android.sourceSets.maybeCreate(variant.name).assets.srcDirs += assetsDir
  }

  def fingerprintAssetsDir = file("$buildDir/generated/assets/expo-constants-fingerprint")

  def createFingerprintTask = tasks.register('createExpoFingerprint', Exec) {
    description = 'expo-constants: Embed the project fingerprint (app.fingerprint) in debug builds.'

    doFirst {
      fingerprintAssetsDir.deleteDir()
      fingerprintAssetsDir.mkdirs()
    }

    // The fingerprint hashes sources across the whole project, so always regenerate it
    outputs.upToDateWhen { false }
    outputs.dir fingerprintAssetsDir

    workingDir projectRoot

    if (Os.isFamily(Os.FAMILY_WINDOWS)) {
      commandLine("cmd", "/c", *nodeExecutableAndArgs, "$expoConstantsDir/scripts/createFingerprintFile.js", projectRoot, fingerprintAssetsDir, "android")
    } else {
      commandLine(*nodeExecutableAndArgs, "$expoConstantsDir/scripts/createFingerprintFile.js", projectRoot, fingerprintAssetsDir, "android")
    }
  }

  project.android.libraryVariants.all { variant ->
    if (!variant.buildType.debuggable) {
      return
    }
    variant.preBuildProvider.configure { it.dependsOn(createFingerprintTask) }
    project.android.sourceSets.maybeCreate(variant.buildType.name).assets.srcDirs += fingerprintAssetsDir
  }
}
