#!/usr/bin/env bash
# Launch BikeControl. Always builds first via `cargo tauri build`, because a
# plain `cargo build` produces a binary wired to localhost:1420 that shows a
# BLACK WINDOW unless a Vite dev server happens to be running. Incremental
# builds take seconds, and this removes a whole class of confusion.
#
# `pipefail` is load-bearing. This script used to end the build line with
# `| tail -3`, which meant the exit status came from `tail` and was always 0:
# a build that failed to compile printed three lines of error, `set -e` saw
# success, and the script went on to launch whatever binary was already in
# target/ — silently, and possibly hours old. Every symptom of that looks like
# a code change that "did not work", because the code being run is not the code
# on disk. A failed build must stop here.
set -euo pipefail

ROOT="$(cd "$(dirname "$0")" && pwd)"
LOG="$ROOT/bikecontrol.log"
BIN="$ROOT/target/debug/bikecontrol-app"
BUILD_LOG="$ROOT/target/last-build.log"

# WebKitGTK 2.52 on Wayland + Intel paints black rectangles via its DMABUF
# renderer; disabling it costs nothing here (the UI is 2D canvas and CSS).
export WEBKIT_DISABLE_DMABUF_RENDERER=1
export WEBKIT_DISABLE_COMPOSITING_MODE=1
export RUST_LOG="${RUST_LOG:-debug,btleplug=info,tao=warn,wry=warn}"

echo "building (embeds the frontend — this is what avoids the black window)..."
mkdir -p "$(dirname "$BUILD_LOG")"

# Quiet on success, complete on failure. Piping straight to `tail` would hide
# the first error of a cascade, which is usually the only one that matters.
if ( cd "$ROOT/src-tauri" && cargo tauri build --debug --no-bundle ) >"$BUILD_LOG" 2>&1; then
  tail -3 "$BUILD_LOG"
else
  status=$?
  echo
  echo "════════════════════════════════════════════"
  echo "  BUILD FAILED — not launching."
  echo "════════════════════════════════════════════"
  echo
  cat "$BUILD_LOG"
  echo
  if [[ -x $BIN ]]; then
    echo "There IS an older binary at $BIN (built $(date -r "$BIN" '+%Y-%m-%d %H:%M:%S'))."
    echo "It is deliberately NOT being launched: running stale code against new"
    echo "expectations is how an afternoon disappears."
  fi
  exit $status
fi

if [[ ! -x $BIN ]]; then
  echo "build reported success but $BIN is missing" >&2
  exit 1
fi

# Say what is actually about to run. The whole point of the machinery above is
# that this line can be trusted, so print it where it cannot be missed.
echo "=== BikeControl $(date '+%H:%M:%S') ===" > "$LOG"
echo "launching $BIN"
echo "  built:   $(date -r "$BIN" '+%Y-%m-%d %H:%M:%S')"
echo "  logging: $LOG"
exec "$BIN" "$@" 2>&1 | tee -a "$LOG"
