#!/usr/bin/env bash
set -euo pipefail

MODE="${1:-debug}"

if [[ "$MODE" != "debug" && "$MODE" != "release" ]]; then
  echo "Usage: $0 [debug|release]" >&2
  exit 2
fi

PROJECT_ROOT="/home/anthony/Documents/Projects/GameTime"
BUILD_ENV_ROOT="$PROJECT_ROOT/.ideai/build-env"
SDK_COPY="$BUILD_ENV_ROOT/flutter-sdk"
HOME_DIR="$BUILD_ENV_ROOT/home"
GRADLE_DIR="$BUILD_ENV_ROOT/gradle"
PUB_CACHE_DIR="$BUILD_ENV_ROOT/pub-cache"
TMP_DIR="$BUILD_ENV_ROOT/tmp"
ANDROID_HOME="/opt/android-sdk"
JAVA_HOME="/usr/lib/jvm/java-21-openjdk"
FLUTTER_BIN="$SDK_COPY/bin/flutter"

mkdir -p "$BUILD_ENV_ROOT" "$HOME_DIR/.config" "$HOME_DIR/.local/share" "$HOME_DIR/.cache" "$GRADLE_DIR" "$PUB_CACHE_DIR" "$TMP_DIR"

if [[ ! -x "$FLUTTER_BIN" ]]; then
  cp -a /opt/flutter "$SDK_COPY"
fi

export HOME="$HOME_DIR"
export XDG_CONFIG_HOME="$HOME_DIR/.config"
export XDG_DATA_HOME="$HOME_DIR/.local/share"
export XDG_CACHE_HOME="$HOME_DIR/.cache"
export GRADLE_USER_HOME="$GRADLE_DIR"
export PUB_CACHE="$PUB_CACHE_DIR"
export TMPDIR="$TMP_DIR"
export TMP="$TMP_DIR"
export TEMP="$TMP_DIR"
export JAVA_TOOL_OPTIONS="-Djava.io.tmpdir=$TMP_DIR"
export GRADLE_OPTS="-Djava.io.tmpdir=$TMP_DIR"
export ANDROID_HOME
export JAVA_HOME
export PATH="$JAVA_HOME/bin:$ANDROID_HOME/cmdline-tools/latest/bin:$ANDROID_HOME/platform-tools:$PATH"

cd "$PROJECT_ROOT"

"$FLUTTER_BIN" --disable-analytics pub get
"$FLUTTER_BIN" build apk "--$MODE"

APK_PATH="$PROJECT_ROOT/build/app/outputs/flutter-apk/app-$MODE.apk"
echo "APK built at: $APK_PATH"
