#!/usr/bin/env bash
#
# Please set the environment variable ANDROID_NDK
# before running this script

# Inside the $ANDROID_NDK directory, you can find a binary ndk-build
# and some other files like the file "build/cmake/android.toolchain.cmake"

set -ex

log() {
  # This function is from espnet
  local fname=${BASH_SOURCE[1]##*/}
  echo -e "$(date '+%Y-%m-%d %H:%M:%S') (${fname}:${BASH_LINENO[0]}:${FUNCNAME[1]}) $*"
}

SHERPA_ONNX_VERSION=$(grep "SHERPA_ONNX_VERSION" ./CMakeLists.txt  | cut -d " " -f 2  | cut -d '"' -f 2)

log "Building Speaker identification APK for sherpa-onnx v${SHERPA_ONNX_VERSION}"

export SHERPA_ONNX_ENABLE_TTS=OFF

log "====================arm64-v8a================="
./build-android-arm64-v8a.sh
log "====================armv7-eabi================"
./build-android-armv7-eabi.sh
log "====================x86-64===================="
./build-android-x86-64.sh
log "====================x86===================="
./build-android-x86.sh

mkdir -p apks

{% for model in model_list %}

pushd ./android/SherpaOnnxSpeakerDiarization/app/src/main/assets/

ls -lh

segmentation_model_name={{ model.segmentation.model_name }}
segmentation_short_name={{ model.segmentation.short_name }}

embedding_model_name={{ model.embedding.model_name }}
embedding_short_name={{ model.embedding.short_name }}

curl -SL -O https://github.com/k2-fsa/sherpa-onnx/releases/download/speaker-segmentation-models/$segmentation_model_name.tar.bz2
tar xvf $segmentation_model_name.tar.bz2
rm $segmentation_model_name.tar.bz2
mv $segmentation_model_name/model.onnx segmentation.onnx
rm -rf $segmentation_model_name

curl -SL -O https://github.com/k2-fsa/sherpa-onnx/releases/download/speaker-recongition-models/$embedding_model_name.onnx
mv $embedding_model_name.onnx embedding.onnx

echo "pwd: $PWD"
ls -lh

popd

for arch in arm64-v8a armeabi-v7a x86_64 x86; do
  log "------------------------------------------------------------"
  log "build speaker diarization apk for $arch"
  log "------------------------------------------------------------"
  src_arch=$arch
  if [ $arch == "armeabi-v7a" ]; then
    src_arch=armv7-eabi
  elif [ $arch == "x86_64" ]; then
    src_arch=x86-64
  fi

  ls -lh ./build-android-$src_arch/install/lib/*.so

  cp -v ./build-android-$src_arch/install/lib/*.so ./android/SherpaOnnxSpeakerDiarization/app/src/main/jniLibs/$arch/

  pushd ./android/SherpaOnnxSpeakerDiarization
  ./gradlew build
  popd

  mv android/SherpaOnnxSpeakerDiarization/app/build/outputs/apk/debug/app-debug.apk ./apks/sherpa-onnx-${SHERPA_ONNX_VERSION}-$arch-speaker-diarization-$segmentation_short_name-$embedding_short_name.apk
  ls -lh apks
  rm -v ./android/SherpaOnnxSpeakerDiarization/app/src/main/jniLibs/$arch/*.so
done

rm -rf ./android/SherpaOnnxSpeakerDiarization/app/src/main/assets/*.onnx

{% endfor %}

ls -lh apks
