#!/usr/bin/env bash
# Run Tauri CLI for a suite app (nested layout under mobile/apps/<id>/src-tauri).
# Usage (from repo root): bash mobile/scripts/tauri-app.sh ultimail android init
set -euo pipefail

APP="${1:?app id (ultimail, ultidrive, ulticalmeet, ultiai, contacts)}"
shift

ROOT="$(cd "$(dirname "$0")/../.." && pwd)"
APP_DIR="$ROOT/mobile/apps/$APP"

# Tauri spawns rustup/cargo without a login shell — ensure toolchain + Android SDK on PATH.
if [[ -f "$HOME/.cargo/env" ]]; then
  # shellcheck disable=SC1091
  source "$HOME/.cargo/env"
fi
export PATH="$HOME/.cargo/bin:${PATH:-}"

export ANDROID_HOME="${ANDROID_HOME:-$HOME/Library/Android/sdk}"
if [[ -d "$ANDROID_HOME/ndk" ]]; then
  export NDK_HOME="${NDK_HOME:-$ANDROID_HOME/ndk/$(ls -1 "$ANDROID_HOME/ndk" | sort -V | tail -1)}"
fi
if [[ -x "/Applications/Android Studio.app/Contents/jbr/Contents/Home/bin/java" ]]; then
  export JAVA_HOME="${JAVA_HOME:-/Applications/Android Studio.app/Contents/jbr/Contents/Home}"
fi
export PATH="$ANDROID_HOME/platform-tools:$ANDROID_HOME/emulator:${JAVA_HOME:+$JAVA_HOME/bin:}$PATH"

if ! command -v rustup >/dev/null 2>&1; then
  echo "rustup not found on PATH. Install via https://rustup.rs and ensure ~/.cargo/bin is in PATH." >&2
  exit 1
fi

if [[ ! -f "$APP_DIR/src-tauri/tauri.conf.json" ]]; then
  echo "No tauri.conf.json for app '$APP' at $APP_DIR/src-tauri" >&2
  exit 1
fi

CONFIG="$APP_DIR/src-tauri/tauri.conf.json"
cd "$ROOT"
export ULTI_REPO_ROOT="$ROOT"
export TAURI_CLI_CONFIG_DEPTH="${TAURI_CLI_CONFIG_DEPTH:-5}"
exec pnpm exec tauri "$@" --config "$CONFIG"
