# shellcheck shell=bash
# Toolchain + shared locations for the GCP dev VM (petav3-dev).
# Sourced by ~/.bashrc (above its interactive guard) and by every tool/dev script.
# Safe to source repeatedly. Nothing here is secret.

_pl_tool_dir="$(cd "$(dirname "${BASH_SOURCE[0]}")" && pwd)"
export PL_APP_DIR="$(cd "$_pl_tool_dir/../.." && pwd)"
export PL_BACKEND_DIR="${PL_BACKEND_DIR:-$(cd "$PL_APP_DIR/.." && pwd)/peta}"
unset _pl_tool_dir

export PL_TMP=/tmp/propertylab
export PL_RUN_LOG="$PL_TMP/flutter-run.log"
export PL_SHOT="$PL_TMP/shot.png"
export PL_WEB_PORT="${PL_WEB_PORT:-8080}"
export PL_CDP_PORT="${PL_CDP_PORT:-9222}"
export PL_CHROME_PROFILE="$PL_TMP/chrome-profile"

export ANDROID_HOME="${ANDROID_HOME:-$HOME/android-sdk}"
export ANDROID_SDK_ROOT="$ANDROID_HOME"
export JAVA_HOME="${JAVA_HOME:-/usr/lib/jvm/java-17-openjdk-amd64}"
export CHROME_EXECUTABLE="${CHROME_EXECUTABLE:-/usr/bin/google-chrome}"
case ":$PATH:" in
  *":$HOME/fvm/bin:"*) ;;
  *) export PATH="$HOME/fvm/bin:$ANDROID_HOME/cmdline-tools/latest/bin:$ANDROID_HOME/platform-tools:$ANDROID_HOME/emulator:$PATH" ;;
esac

# First online Android emulator/device serial, or empty. (No KVM on the e2 VM
# today, so this is normally empty and the scripts fall back to Flutter Web.)
pl_device() {
  command -v adb >/dev/null 2>&1 || return 0
  adb devices 2>/dev/null | awk '/^(emulator-[0-9]+|[0-9A-Za-z]+)\tdevice$/ {print $1; exit}'
}

# Headless Chrome with the DevTools protocol on $PL_CDP_PORT, kept alive in
# tmux session "chrome". Idempotent.
pl_ensure_chrome() {
  mkdir -p "$PL_CHROME_PROFILE"
  curl -fs "http://127.0.0.1:$PL_CDP_PORT/json/version" >/dev/null 2>&1 && return 0
  tmux kill-session -t chrome 2>/dev/null || true
  tmux new -d -s chrome "'$CHROME_EXECUTABLE' --headless=new \
    --remote-debugging-port=$PL_CDP_PORT --remote-allow-origins=* \
    --no-sandbox --use-angle=swiftshader --enable-unsafe-swiftshader \
    --disable-dev-shm-usage --no-first-run --hide-scrollbars \
    --window-size=412,915 --user-data-dir='$PL_CHROME_PROFILE' about:blank"
  for _ in $(seq 1 60); do
    curl -fs "http://127.0.0.1:$PL_CDP_PORT/json/version" >/dev/null 2>&1 && return 0
    sleep 0.25
  done
  echo "headless Chrome did not come up (see: tmux a -t chrome)" >&2
  return 1
}
