#!/usr/bin/env bash
# Deploy the chatter binary to the tablet and run it on the e-paper display.
#
# Usage: scripts/deploy-and-run.sh [path-to-binary]
#   default binary: build/chatter
#
# Requires: `ssh chatter` working (see doc/tablet_access.md).
#
# IMPORTANT lessons baked in here:
#  * The e-paper framebuffer is a singleton guarded by an flock
#    (/tmp/epframebuffer.lock). Only ONE process may hold it. A stranded
#    instance blanks the panel for everyone, so we always stop the previous
#    chatter unit first.
#  * Launch as a transient systemd service (systemd-run), NOT an ssh background
#    job: that detaches cleanly (no held SSH channel) and is stoppable via
#    `systemctl stop chatter`.
#  * xochitl owns the display while running, so stop it first (pre-authorized
#    during development). Run scripts/restore-xochitl.sh to bring it back.
set -euo pipefail
cd "$(dirname "$0")/.."

HOST="chatter"
DEST="/home/root/chatter"   # under /home, NOT the nearly-full rootfs

# Use an explicit binary if given; else a fresh local build; else the prebuilt.
BIN="${1:-}"
if [ -z "$BIN" ]; then
  if [ -f build/chatter ]; then BIN=build/chatter; else BIN=dist/chatter; fi
fi
[ -f "$BIN" ] || { echo "binary not found: $BIN (build it, or use the prebuilt dist/chatter)"; exit 1; }

echo ">> stopping any previous chatter + xochitl (release the panel lock)"
ssh "$HOST" 'systemctl stop chatter 2>/dev/null; systemctl reset-failed chatter 2>/dev/null; systemctl stop xochitl 2>/dev/null; sleep 1'

echo ">> deploying $(basename "$BIN") to $HOST:$DEST"
ssh "$HOST" "mkdir -p $DEST"
scp "$BIN" "$HOST:$DEST/"

echo ">> launching chatter as a transient systemd service"
# LD_LIBRARY_PATH lets the loader resolve libqsgepaper.so (linked for the private
# EPScreenModeItem type), which lives in the scenegraph plugin dir.
ssh "$HOST" "systemd-run --unit=chatter --collect \
  --setenv=QT_QUICK_BACKEND=epaper \
  --setenv=LD_LIBRARY_PATH=/usr/lib/plugins/scenegraph \
  --working-directory=$DEST \
  $DEST/$(basename "$BIN") -platform epaper"

sleep 4
ssh "$HOST" 'echo "chatter: $(systemctl is-active chatter)"'
echo ">> logs: ssh chatter 'journalctl -u chatter -f'"
echo ">> stop:  ssh chatter 'systemctl stop chatter'  (then scripts/restore-xochitl.sh)"
