#!/bin/bash
set -e

SCRIPT_DIR="$(cd "$(dirname "$0")" && pwd)"
GO_DIR="$SCRIPT_DIR/go"
ANDROID_DIR="$SCRIPT_DIR/android"
LIBS_DIR="$ANDROID_DIR/app/libs"

echo "=== TeamSpeak Mobile Build Script ==="

# 1. Check dependencies
echo ""
echo "[1/4] Checking dependencies..."

if ! command -v go &>/dev/null; then
    echo "ERROR: Go not installed. Download from https://go.dev/dl/"
    exit 1
fi
echo "  Go: $(go version)"

if ! command -v gomobile &>/dev/null; then
    echo "  gomobile not found, installing..."
    go install golang.org/x/mobile/cmd/gomobile@latest
    gomobile init
fi
echo "  gomobile: OK"

if [ -z "$ANDROID_HOME" ]; then
    echo "ERROR: ANDROID_HOME not set"
    exit 1
fi
echo "  Android SDK: $ANDROID_HOME"

# 2. Download Go dependencies
echo ""
echo "[2/4] Downloading Go dependencies..."
cd "$GO_DIR"
go mod tidy

# 3. Build Go -> AAR
echo ""
echo "[3/4] Building Android libopus and Go bridge -> AAR..."
"$GO_DIR/build-opus-android.sh"
mkdir -p "$LIBS_DIR"
export JAVA_TOOL_OPTIONS="-Dfile.encoding=UTF-8 -Dsun.jnu.encoding=UTF-8"
# Required: include the Android CGo/libopus decoder instead of the stub.
export CGO_ENABLED=1
gomobile bind -target=android -androidapi=26 -ldflags="-linkmode=external -extldflags=-Wl,--hash-style=both" -o "$LIBS_DIR/teamspeak.aar" ./teamspeak
echo "  Output: $LIBS_DIR/teamspeak.aar"

# 4. Build Android app
echo ""
echo "[4/4] Building Android app..."
cd "$ANDROID_DIR"
if [ -f "gradlew" ]; then
    ./gradlew assembleDebug
else
    echo "  WARNING: gradlew not found, please sync in Android Studio"
    echo "  Or run: gradle wrapper"
fi

echo ""
echo "=== Build Complete ==="
echo "APK: $ANDROID_DIR/app/build/outputs/apk/debug/app-debug.apk"
