#!/usr/bin/env bash
set -euo pipefail

# Builds the vendored libopus source for every ABI gomobile supports and puts
# static archives where voice_decoder_factory_android.go links them. This is a
# build-time dependency only; no native library needs to be loaded separately.
ROOT="$(cd "$(dirname "$0")/.." && pwd)"
OPUS_SOURCE="$ROOT/android/app/src/main/cpp/third_party/opus"
OUTPUT="$ROOT/go/teamspeak/.opus/lib"
SDK_ROOT="${ANDROID_HOME:-${ANDROID_SDK_ROOT:-}}"

if [[ -z "$SDK_ROOT" && -f "$ROOT/android/local.properties" ]]; then
  SDK_ROOT="$(sed -n 's#^sdk.dir=##p' "$ROOT/android/local.properties" | sed 's#\\\\#/#g')"
fi
if [[ -z "$SDK_ROOT" ]]; then
  echo "ANDROID_HOME or ANDROID_SDK_ROOT must point to an Android SDK" >&2
  exit 1
fi

if [[ -n "${ANDROID_NDK_HOME:-}" ]]; then
  NDK="$ANDROID_NDK_HOME"
elif [[ -n "${ANDROID_NDK_ROOT:-}" ]]; then
  NDK="$ANDROID_NDK_ROOT"
else
  NDK="$(ls -d "$SDK_ROOT"/ndk/* 2>/dev/null | sort -V | tail -n 1 || true)"
fi
if [[ -z "$NDK" || ! -d "$NDK" ]]; then
  echo "Android NDK not found under $SDK_ROOT/ndk" >&2
  exit 1
fi

CMAKE="${CMAKE:-$SDK_ROOT/cmake/3.22.1/bin/cmake}"
if [[ ! -x "$CMAKE" ]]; then
  CMAKE="cmake"
fi
NINJA="$(dirname "$CMAKE")/ninja.exe"
if [[ ! -x "$NINJA" ]]; then
  NINJA="ninja"
fi

for abi in armeabi-v7a arm64-v8a x86 x86_64; do
  build="$ROOT/go/teamspeak/.opus/build/$abi"
  install="$ROOT/go/teamspeak/.opus/install/$abi"
  "$CMAKE" -S "$OPUS_SOURCE" -B "$build" -G Ninja -DCMAKE_MAKE_PROGRAM="$NINJA" \
    -DCMAKE_TOOLCHAIN_FILE="$NDK/build/cmake/android.toolchain.cmake" \
    -DANDROID_ABI="$abi" -DANDROID_PLATFORM=android-26 \
    -DCMAKE_BUILD_TYPE=Release -DOPUS_BUILD_SHARED_LIBRARY=OFF \
    -DOPUS_BUILD_PROGRAMS=OFF -DOPUS_BUILD_TESTING=OFF \
    -DOPUS_INSTALL_PKG_CONFIG_MODULE=OFF -DOPUS_INSTALL_CMAKE_CONFIG_MODULE=OFF \
    -DCMAKE_INSTALL_PREFIX="$install"
  "$CMAKE" --build "$build" --config Release
  "$CMAKE" --install "$build" --config Release
  mkdir -p "$OUTPUT/$abi"
  cp "$install/lib/libopus.a" "$OUTPUT/$abi/libopus.a"
done
