#!/usr/bin/env bash
#
# Wrapper script for telora-daemon that restarts it after a self-update.
#
# Usage:
#   telora-daemon-wrapper.sh [daemon args...]
#
# Restart-after-update contract (stated once, in the daemon package:
# src/update/restart-contract.ts): a daemon run by a supervisor that restarts
# on exit 75 exits 75 after installing a newer version of itself and spawns
# nothing; the supervisor starts the new version. This wrapper IS such a
# supervisor, and declares itself by exporting TELORA_DAEMON_SUPERVISOR=wrapper
# so the daemon exits 75 to it instead of re-exec'ing a detached child.
#
# For systemd users, you can instead run telora-daemon directly from a unit
# with, in the [Service] section:
#   Restart=on-failure
#   RestartForceExitStatus=75
# (see docs/DAEMON_SETUP.md).

set -euo pipefail

export TELORA_DAEMON_SUPERVISOR=wrapper

# Default to 'run' subcommand if no args given
ARGS=("$@")
if [ ${#ARGS[@]} -eq 0 ]; then
  ARGS=("run")
fi

while true; do
  # `|| rc=$?` keeps a non-zero exit from tripping `set -e` before it is read.
  rc=0
  telora-daemon "${ARGS[@]}" || rc=$?
  if [ "$rc" -eq 75 ]; then
    echo "[wrapper] Daemon exited with code 75 (auto-updated), restarting..."
    continue
  fi
  exit "$rc"
done
