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

cd /workspace

export VITE_API_URL="${VITE_API_URL:-${PUBLIC_API_URL:-http://localhost:3000}}"
export VITE_FRONTEND_URL="${VITE_FRONTEND_URL:-${PUBLIC_FRONTEND_URL:-http://localhost:3002}}"
export ANDROID_HOME="${ANDROID_HOME:-/opt/android-sdk}"
export ANDROID_SDK_ROOT="${ANDROID_SDK_ROOT:-${ANDROID_HOME}}"

if [ -z "${ANDROID_NDK_HOME:-}" ]; then
  NDK_DIR="$(find "${ANDROID_HOME}/ndk" -mindepth 1 -maxdepth 1 -type d 2>/dev/null | sort -V | tail -n 1 || true)"
  if [ -n "${NDK_DIR}" ]; then
    export ANDROID_NDK_HOME="${NDK_DIR}"
    export NDK_HOME="${NDK_DIR}"
  fi
fi

echo "==> Android SDK: ${ANDROID_HOME}"
echo "==> Android NDK: ${ANDROID_NDK_HOME:-не найден}"

if [ -z "${ANDROID_NDK_HOME:-}" ] || [ ! -d "${ANDROID_NDK_HOME}" ]; then
  echo "Android NDK не найден в ${ANDROID_HOME}/ndk. Используйте Android SDK image с предустановленным NDK или примонтируйте SDK с NDK." >&2
  exit 1
fi

mkdir -p /out

echo "==> Проверка web-сборки tauri_app"
npm --workspace @lendry/tauri-app run build

cd /workspace/tauri_app

if [ -d "src-tauri/gen/android" ]; then
  echo "==> Очистка предыдущего Android проекта Tauri"
  rm -rf src-tauri/gen/android
fi

echo "==> Инициализация Android проекта Tauri"
npm run android:init -- --ci || npm run android:init

if [ -n "${ANDROID_GRADLE_PLUGIN_VERSION:-}" ]; then
  echo "==> Переопределение Android Gradle Plugin: ${ANDROID_GRADLE_PLUGIN_VERSION}"
  find src-tauri/gen/android \
    -type f \
    \( -name '*.gradle' -o -name '*.gradle.kts' -o -name '*.toml' \) \
    -print0 \
    | xargs -0 sed -i -E "s/(com\\.android\\.tools\\.build:gradle:)[0-9]+\\.[0-9]+\\.[0-9]+/\\1${ANDROID_GRADLE_PLUGIN_VERSION}/g; s/(com\\.android\\.application[\"']? version[[:space:]]*=?[[:space:]]*[\"'])[0-9]+\\.[0-9]+\\.[0-9]+/\\1${ANDROID_GRADLE_PLUGIN_VERSION}/g"
fi

echo "==> Сборка Android APK"
npm run tauri -- android build --apk

APK_PATH="$(find /workspace/tauri_app/src-tauri/gen/android -type f -name '*.apk' | sort | tail -n 1 || true)"

if [ -z "${APK_PATH}" ] || [ ! -f "${APK_PATH}" ]; then
  echo "APK не найден после сборки" >&2
  find /workspace/tauri_app/src-tauri/gen/android -maxdepth 8 -type f | sort >&2 || true
  exit 1
fi

cp "${APK_PATH}" /out/lendry-id.apk
chmod 0644 /out/lendry-id.apk

echo "==> APK готов: /out/lendry-id.apk"
ls -lh /out/lendry-id.apk
