#!/bin/bash
# Build script for Picocrypt-NG Android app
# This script cleans and rebuilds the debug APK for development

set -e  # Exit on error

# Get the directory where this script is located
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
cd "$SCRIPT_DIR"

echo "Building Picocrypt-NG Android app..."
echo "Working directory: $SCRIPT_DIR"

JAVA_BIN="${JAVA_HOME:+$JAVA_HOME/bin/java}"
if [ -z "$JAVA_BIN" ] || [ ! -x "$JAVA_BIN" ]; then
    JAVA_BIN="$(command -v java || true)"
fi

if [ -z "$JAVA_BIN" ]; then
    echo "Error: Java runtime not found. JDK 17 is required." >&2
    exit 1
fi

JAVA_VERSION="$("$JAVA_BIN" -version 2>&1 | sed -n 's/.*version "\(.*\)".*/\1/p' | head -n1)"
JAVA_MAJOR="${JAVA_VERSION%%.*}"
if [ "$JAVA_MAJOR" = "1" ]; then
    JAVA_MAJOR="$(echo "$JAVA_VERSION" | cut -d. -f2)"
fi

if [ "$JAVA_MAJOR" != "17" ]; then
    echo "Error: JDK 17 is required for the native Android build." >&2
    echo "  Detected Java version: ${JAVA_VERSION:-unknown}" >&2
    echo "  Set JAVA_HOME to a JDK 17 installation before running this script." >&2
    exit 1
fi

# Ensure gradlew is executable
chmod +x gradlew

# Clean previous build
echo "Cleaning previous build..."
./gradlew clean

# Build debug APK
echo "Building debug APK..."
./gradlew assembleDebug

# Show output location
APK_PATH="app/build/outputs/apk/debug/app-debug.apk"
if [ -f "$APK_PATH" ]; then
    echo ""
    echo "✓ Build successful!"
    echo "  APK location: $APK_PATH"
    echo "  File size: $(du -h "$APK_PATH" | cut -f1)"
else
    echo "✗ Build failed - APK not found at $APK_PATH"
    exit 1
fi
