#!/bin/bash
# Build + install HomelabMFA on device
# Usage:
#   ./deploy.sh           → connected device/emulator
#   ./deploy.sh wifi      → phone via ADB WiFi
#   ./deploy.sh release   → build signed release APK
set -e

export ANDROID_HOME=~/android-sdk
export PATH="$ANDROID_HOME/platform-tools:$ANDROID_HOME/emulator:$PATH"
GRADLE=~/gradle/gradle-8.6/bin/gradle
PKG=me.khodak.mfa

if [[ "$1" == "wifi" ]]; then
    PHONE_IP="${PHONE_IP:-$(cat .phone-ip 2>/dev/null)}"
    if [[ -z "$PHONE_IP" ]]; then
        read -rp "Phone IP address: " PHONE_IP
        echo "$PHONE_IP" > .phone-ip
    fi
    adb connect "$PHONE_IP:5555" 2>&1 | head -3
fi

if [[ "$1" == "release" ]]; then
    # Generate keystore if needed
    if [[ ! -f app/homelab-mfa-release.keystore ]]; then
        echo "Generating release keystore..."
        keytool -genkeypair -v \
            -keystore app/homelab-mfa-release.keystore \
            -alias homelab-mfa \
            -keyalg RSA -keysize 2048 -validity 10000 \
            -storepass "HomelabMFA2026!" -keypass "HomelabMFA2026!" \
            -dname "CN=Homelab MFA, O=khodak.me, C=US"
    fi
    echo "Building release APK..."
    $GRADLE assembleRelease --no-daemon -q
    APK=app/build/outputs/apk/release/app-release.apk
    echo "Release APK: $APK"

    # Send via ntfy
    NTFY_TOKEN="tk_gdaagqpdpoig01qkpq4jn0rri1rek"
    SIZE=$(du -sh "$APK" | cut -f1)
    curl -s -H "Authorization: Bearer $NTFY_TOKEN" \
         -H "Title: HomelabMFA APK ready ($SIZE)" \
         -H "Tags: shield" \
         -H "Attach: $(realpath $APK)" \
         -H "Actions: view, Download APK, https://gitea.khodak.me/amir/homelab-mfa/releases/latest" \
         "https://ntfy.khodak.me/homelab" -d "HomelabMFA release build ready. Install and set up biometrics." || true
    echo "Done."
    exit 0
fi

echo "Building debug APK..."
$GRADLE assembleDebug --no-daemon -q
APK=app/build/outputs/apk/debug/app-debug.apk
echo "Build OK"

DEVICES=$(adb devices | awk '/device$/{print $1}')
if [[ -z "$DEVICES" ]]; then
    echo "No device connected."
    exit 1
fi

adb install -r "$APK"
echo "Installed. Launch HomelabMFA from app drawer to verify, or tap an Approve action in ntfy."
