#!/usr/bin/env bash

set -e

# Directory where the script is located
SCRIPT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
BIN_DIR="$SCRIPT_DIR/.bin"
BUNDLETOOL_VERSION=1.18.1

BUNDLETOOL_VERSION_STR="$(echo "$BUNDLETOOL_VERSION" | tr '.' '_')"
BUNDLETOOL_JAR="$BIN_DIR/bundletool_$BUNDLETOOL_VERSION_STR.jar"

# Check if Java is available
if ! command -v java &>/dev/null; then
  echo "Error: Java is not installed or not in PATH"
  echo "Please install Java or make sure it's in your PATH"
  exit 1
fi

# Create bin directory if it doesn't exist
mkdir -p "$BIN_DIR"

# Download bundletool if not present
if [ ! -f "$BUNDLETOOL_JAR" ]; then
  tmp_file=$(mktemp)
  trap 'rm -f "$tmp_file"' EXIT
  echo "Downloading bundletool version $BUNDLETOOL_VERSION..."
  curl -L --progress-bar "https://github.com/google/bundletool/releases/download/$BUNDLETOOL_VERSION/bundletool-all-$BUNDLETOOL_VERSION.jar" -o "$tmp_file"
  mv "$tmp_file" "$BUNDLETOOL_JAR"
fi

exec java -jar "$BUNDLETOOL_JAR" "$@"
