#!/bin/bash
# pgv3-supervisor.sh — simple respawn loop for the pear-git-v3 launcher.
#
# Works with OTA auto-respawn: when the daemon sees a tree update, it
# exits (if PGV3_AUTO_RESPAWN=1) and this loop relaunches it against
# the freshly-materialized install tree. Also handles crashes.
#
# Inherits env from the parent shell. Typical use:
#
# PEAR_GIT_STORAGE=$HOME/pgv3-storage \
# PEAR_GIT_HTTP=4040 \
# PEAR_GIT_HOST=0.0.0.0 \
# PGV3_AUTO_RESPAWN=1 \
# scripts/pgv3-supervisor.sh
#
# Stops looping on SIGTERM / SIGINT from the supervisor itself. The
# inner daemon receives signals transparently via exec.
set -u
LAUNCHER="${PGV3_LAUNCHER:-$HOME/.local/bin/pear-git-v3}"
BACKOFF_MIN=2
BACKOFF_MAX=30
FAST_FAIL_THRESHOLD_S=5
trap 'echo "[supervisor] received signal; exiting" >&2; exit 0' INT TERM
backoff=$BACKOFF_MIN
while true; do
echo "[supervisor] starting $LAUNCHER" >&2
start_epoch=$(date +%s)
"$LAUNCHER" "$@"
status=$?
run_s=$(( $(date +%s) - start_epoch ))
echo "[supervisor] daemon exited status=$status after ${run_s}s" >&2
# If the daemon ran long enough, reset backoff. Short-lived exits
# (startup crashes) use exponential backoff so we don't spin.
if [ "$run_s" -ge "$FAST_FAIL_THRESHOLD_S" ]; then
backoff=$BACKOFF_MIN
fi
echo "[supervisor] respawn in ${backoff}s..." >&2
sleep "$backoff"
# Exponential up to max
backoff=$(( backoff * 2 ))
if [ "$backoff" -gt "$BACKOFF_MAX" ]; then backoff=$BACKOFF_MAX; fi
done