#!/bin/bash
# The ONLY sanctioned way to deploy shotlog locally. Build -> install (both
# PATH copies) -> restart broker -> verify served stamp -> REFRESH EVERY LIVE
# SURFACE. The human must SEE updates without doing anything (John, 2026-07-18:
# "if you make changes you have to refresh your surfaces so i see your
# updates" ... "always do that").
#
# Two refresh layers, on purpose:
#   1. boot-stamp handshake: every restart changes the welcome stamp, so any
#      connected page reloads itself once on WS reconnect.
#   2. this script ALSO hard-refreshes the named webview tab and nudges the
#      pup session, because a page mid-crash can miss a reconnect.
set -e
cd "$(dirname "$0")/.."
V=$(grep -m1 '^version' Cargo.toml | sed 's/.*"\(.*\)".*/\1/')

touch src/main.rs   # cargo fingerprints skip re-embedding include_str! edits otherwise
cargo build --release

for D in "$HOME/.local/bin" /usr/local/bin; do
  [ -d "$D" ] || continue
  if [ -w "$D" ]; then cp target/release/adom-shotlog "$D/.n" && mv "$D/.n" "$D/adom-shotlog"
  else sudo -n cp target/release/adom-shotlog "$D/.n" && sudo -n mv "$D/.n" "$D/adom-shotlog"; fi
  echo "installed $D/adom-shotlog"
done

# Kill by EXACT process name only. The hook self-heal starts the broker as
# `shotlog serve` (argv[0]=shotlog); -f patterns match your own shell. Both
# lessons cost us dearly - see dev-skills.
for P in $(pgrep -x adom-shotlog; pgrep -x shotlog); do kill "$P" 2>/dev/null || true; done
sleep 1

cd /home/adom/project
echo "=== deploy $V $(date '+%m-%d %H:%M:%S') (tools/deploy.sh) ===" >> prod-srv.log
SHOTLOG_AD_TARGET="${SHOTLOG_AD_TARGET:-AdomLapper}" nohup adom-shotlog serve >> prod-srv.log 2>&1 &
sleep 2

SERVED=$(curl -s http://127.0.0.1:8820/log/ | grep -o "APP_VERSION='[^']*'" || true)
case "$SERVED" in *"$V"*) echo "serving: $SERVED" ;; *)
  echo "ERROR: served stamp '$SERVED' does not contain $V - deploy NOT live"; exit 1 ;; esac

# Refresh the webview tab ONLY if it exists (open-or-refresh would create one,
# which must never happen as a deploy side effect on a pup-canvas human).
if adom-cli hydrogen workspace find-tab Shotlog 2>/dev/null | grep -q 'Shotlog'; then
  PROXY="${VSCODE_PROXY_URI/\{\{port\}\}/8820}"
  adom-cli hydrogen webview open-or-refresh --name Shotlog \
    --url "${PROXY}log/?surface=webview" >/dev/null 2>&1 \
    && echo "webview tab refreshed" || echo "WARN: webview refresh failed"
else
  echo "no webview tab open - nothing to refresh there"
fi
# Pup pages reload themselves via the boot-stamp on reconnect; nudge anyway.
adom-desktop --target "${SHOTLOG_AD_TARGET:-AdomLapper}" browser_reload '{"sessionId":"shotlog"}' >/dev/null 2>&1 \
  && echo "pup session nudged" || true
echo "OK: deployed $V and refreshed surfaces."