/*
 * Copyright (c) Meta Platforms, Inc. and affiliates.
 *
 * This source code is licensed under the MIT license found in the
 * LICENSE file in the root directory of this source tree.
 */

plugins {
  id("com.android.library")
  id("com.facebook.hermes.plugins.internal.hermesUtils")
}

buildDir = "${hermesUtils.hermesWs}/build_android/cppruntime"
buildDir.mkdirs()

android {
  namespace = "com.facebook.hermes.cppruntime"
  compileSdk = hermesUtils.compileSdk
  ndkVersion = hermesUtils.ndkVersion

  defaultConfig {
    minSdk = hermesUtils.minSdk
    externalNativeBuild {
      cmake {
        arguments "-DANDROID_STL=c++_shared"
        arguments "-DANDROID_PIE=True"
      }
    }

    ndk {
      abiFilters (*hermesUtils.abis)
    }
  }

  externalNativeBuild {
    cmake {
      version = hermesUtils.cmakeVersion
      path "src/main/cpp/CMakeLists.txt"
      buildStagingDirectory = "${hermesUtils.hermesWs}/staging/cppruntime"
      buildStagingDirectory.mkdirs()
    }
  }

  packagingOptions {
    exclude "**/libstub.so"
  }

  afterEvaluate {
    // Gradle 4/5.0 outputs android-debug.aar and android-release.aar
    // Gradle 5.1 outputs android.aar for both
    // Unify the two by renaming the files afterwards.
    // Neither appear to care whether the original filename actually exists.
    def aarDir = "$buildDir/outputs/aar"
    tasks.named("assembleDebug").configure {
      doLast {
        file("$aarDir/cppruntime-debug.aar").renameTo("${hermesUtils.outputDir}/hermes-cppruntime-debug.aar")
        file("$aarDir/cppruntime.aar").renameTo("${hermesUtils.outputDir}/hermes-cppruntime-debug.aar")
      }
    }
    tasks.named("assembleRelease").configure {
      doLast {
        file("$aarDir/cppruntime-release.aar").renameTo("${hermesUtils.outputDir}/hermes-cppruntime-release.aar")
        file("$aarDir/cppruntime.aar").renameTo("${hermesUtils.outputDir}/hermes-cppruntime-release.aar")
      }
    }
  }
}
