#!/bin/sh
# bob-agent-update — install the latest bob-agent build and restart every
# server instance (#12). Run as root:  sudo bob-agent-update
#
# Fetches the .deb that the Forgejo Actions workflow publishes to the
# "bob-agent" generic package (version "latest") on every push to main,
# installs it with dpkg, then restarts all enabled bob-agent@<user>
# instances so every unix user's server runs the new binary. Restarts are
# lossless: the server drains (in-flight tool work finishes) before exiting.
#
# Configuration via environment (or /etc/bob-agent/update.conf, sourced
# below): BOB_FORGEJO_HOST, BOB_FORGEJO_REPO, BOB_FORGEJO_TOKEN. The token
# is only needed when the repo/package is private; it must be readable by
# root. Run as root.
set -eu

if [ "$(id -u)" -ne 0 ]; then
    echo "bob-agent-update: run me as root (sudo bob-agent-update)" >&2
    exit 1
fi

if [ -f /etc/bob-agent/update.conf ]; then
    # shellcheck disable=SC1091
    . /etc/bob-agent/update.conf
fi

HOST="${BOB_FORGEJO_HOST:-https://git.blahonga.org}"
REPO="${BOB_FORGEJO_REPO:-art/bob-agent}"
PKG="bob-agent"
VERSION="latest"                       # generic-package version on main
OWNER="${REPO%%/*}"

# Forgejo serves generic packages by file id, which changes on every upload:
# scrape the current file id from the package page, then download it. (The
# version page serves the file itself at /files/<id>.)
page="$HOST/$OWNER/-/packages/generic/$PKG/$VERSION"
fileid="$(curl -fsSL "$page" | sed -n 's/.*\/files\/\([0-9][0-9]*\).*/\1/p' | head -1)"
[ -n "$fileid" ] || { echo "could not find the package file on $page" >&2; exit 1; }
url="$page/files/$fileid"
tmp="$(mktemp -d)"
trap 'rm -rf "$tmp"' EXIT
deb="$tmp/bob-agent-latest.deb"

echo "Fetching $url"
if [ -n "${BOB_FORGEJO_TOKEN:-}" ]; then
    curl -fsSL -H "Authorization: token $BOB_FORGEJO_TOKEN" -o "$deb" "$url"
else
    curl -fsSL -o "$deb" "$url"
fi

echo "Installing $deb"
dpkg -i "$deb"

echo "Restarting all bob-agent server instances"
systemctl restart 'bob-agent@*.service'

echo "Done. Restart your client processes to pick up the new binary;"
echo "sessions are server-side, so reattaching keeps the same conversation."
