#!/usr/bin/env bash

set -e

# Check if Android SDK is available
if [ -z "$ANDROID_HOME" ] && [ -z "$ANDROID_SDK" ]; then
  echo "Error: Android SDK not found"
  echo "Please set ANDROID_HOME or ANDROID_SDK environment variable"
  exit 1
fi

# Use ANDROID_SDK_ROOT if available, fallback to ANDROID_HOME
SDK_ROOT="${ANDROID_SDK:-$ANDROID_HOME}"

# Find the latest build-tools version
BUILD_TOOLS_DIR="$SDK_ROOT/build-tools"
if [ ! -d "$BUILD_TOOLS_DIR" ]; then
  echo "Error: Android build-tools not found in $BUILD_TOOLS_DIR"
  echo "Please install Android build-tools through Android SDK Manager"
  exit 1
fi

# Get the latest build-tools version (highest version number)
LATEST_BUILD_TOOLS=$(find "$BUILD_TOOLS_DIR" -maxdepth 1 -type d ! -path "$BUILD_TOOLS_DIR" -exec basename {} \; | sort -V | tail -n 1)
if [ -z "$LATEST_BUILD_TOOLS" ]; then
  echo "Error: No build-tools versions found in $BUILD_TOOLS_DIR"
  echo "Please install Android build-tools through Android SDK Manager"
  exit 1
fi

AAPT_BINARY="$BUILD_TOOLS_DIR/$LATEST_BUILD_TOOLS/aapt"

# Check if aapt2 exists first (preferred), fallback to aapt
AAPT2_BINARY="$BUILD_TOOLS_DIR/$LATEST_BUILD_TOOLS/aapt2"
if [ -f "$AAPT2_BINARY" ]; then
  AAPT_BINARY="$AAPT2_BINARY"
elif [ ! -f "$AAPT_BINARY" ]; then
  echo "Error: Neither aapt nor aapt2 found in $BUILD_TOOLS_DIR/$LATEST_BUILD_TOOLS"
  echo "Please install Android build-tools through Android SDK Manager"
  exit 1
fi

# Make sure the binary is executable
if [ ! -x "$AAPT_BINARY" ]; then
  echo "Error: $AAPT_BINARY is not executable"
  exit 1
fi

# Execute aapt with all provided arguments
exec "$AAPT_BINARY" "$@"
