@echo off
setlocal EnableExtensions EnableDelayedExpansion

rem Builds vendored libopus for each gomobile Android ABI as static archives.
set ROOT=%~dp0..
set OPUS_SOURCE=%ROOT%\android\app\src\main\cpp\third_party\opus
set OUTPUT=%ROOT%\go\teamspeak\.opus\lib

if not "%ANDROID_HOME%"=="" (
  set SDK_ROOT=%ANDROID_HOME%
) else if not "%ANDROID_SDK_ROOT%"=="" (
  set SDK_ROOT=%ANDROID_SDK_ROOT%
) else (
  for /f "tokens=2 delims==" %%A in ('findstr /B "sdk.dir=" "%ROOT%\android\local.properties"') do set SDK_ROOT=%%A
  set SDK_ROOT=%SDK_ROOT:\=\%
)
if "%SDK_ROOT%"=="" (
  echo ANDROID_HOME or ANDROID_SDK_ROOT must point to an Android SDK.
  exit /b 1
)

if not "%ANDROID_NDK_HOME%"=="" (
  set NDK=%ANDROID_NDK_HOME%
) else if not "%ANDROID_NDK_ROOT%"=="" (
  set NDK=%ANDROID_NDK_ROOT%
) else (
  for /f "delims=" %%A in ('dir /B /AD /O-N "%SDK_ROOT%\ndk"') do if not defined NDK set NDK=%SDK_ROOT%\ndk\%%A
)
if not exist "%NDK%\build\cmake\android.toolchain.cmake" (
  echo Android NDK not found under "%SDK_ROOT%\ndk".
  exit /b 1
)

set CMAKE=%SDK_ROOT%\cmake\3.22.1\bin\cmake.exe
if not exist "%CMAKE%" set CMAKE=cmake
for %%A in ("%CMAKE%") do set NINJA=%%~dpAninja.exe
if not exist "%NINJA%" set NINJA=ninja

for %%A in (armeabi-v7a arm64-v8a x86 x86_64) do (
  set BUILD=%ROOT%\go\teamspeak\.opus\build\%%A
  set INSTALL=%ROOT%\go\teamspeak\.opus\install\%%A
  call "%CMAKE%" -S "%OPUS_SOURCE%" -B "!BUILD!" -G Ninja -DCMAKE_MAKE_PROGRAM="%NINJA%" -DCMAKE_TOOLCHAIN_FILE="%NDK%\build\cmake\android.toolchain.cmake" -DANDROID_ABI=%%A -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!" || exit /b 1
  call "%CMAKE%" --build "!BUILD!" --config Release || exit /b 1
  call "%CMAKE%" --install "!BUILD!" --config Release || exit /b 1
  if not exist "%OUTPUT%\%%A" mkdir "%OUTPUT%\%%A"
  copy /Y "!INSTALL!\lib\libopus.a" "%OUTPUT%\%%A\libopus.a" >nul || exit /b 1
)
