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

ROOT_DIR="$(cd "$(dirname "${BASH_SOURCE[0]}")/.." && pwd)"
cd "$ROOT_DIR"

VERSION="${1:-${VERSION:-1.0.2}}"

if [[ ! "$VERSION" =~ ^[0-9]+[.][0-9]+[.][0-9]+$ ]]; then
  echo "VERSION must look like 1.0.2" >&2
  exit 1
fi

IFS=. read -r VERSION_MAJOR VERSION_MINOR VERSION_PATCH <<< "$VERSION"
VERSION_CODE=$((VERSION_MAJOR * 10000 + VERSION_MINOR * 100 + VERSION_PATCH))

export JAVA_HOME="${JAVA_HOME:-/Applications/Android Studio.app/Contents/jbr/Contents/Home}"
export PATH="$JAVA_HOME/bin:$PATH"
export GRADLE_USER_HOME="${GRADLE_USER_HOME:-$ROOT_DIR/.gradle}"

if [[ ! -x "$JAVA_HOME/bin/java" ]]; then
  echo "Java not found at $JAVA_HOME/bin/java" >&2
  echo "Set JAVA_HOME to Android Studio bundled JBR." >&2
  exit 1
fi

perl -0pi -e "s/versionCode\s+\d+/versionCode $VERSION_CODE/" android/app/build.gradle
perl -0pi -e "s/versionName\s+\"[^\"]+\"/versionName \"$VERSION\"/" android/app/build.gradle

npm ci
VITE_API_BASE_URL="${VITE_API_BASE_URL:-https://iwanttoheal.phenomrom.com}" npm run android:sync

(
  cd android
  ./gradlew --no-daemon --stacktrace clean assembleDebug
)

APK="IWantToHeal2-Thor-v$VERSION.apk"
cp android/app/build/outputs/apk/debug/app-debug.apk "$APK"
ls -lh "$APK"
