#!/usr/bin/env bash
# RemoteRig — Pi-side pull updater
# ================================
# Polls the rolling "dev" release on Gitea and, when the published version
# differs from what's installed, downloads + verifies (sha256) + deploys it
# via the existing rollback-capable deploy.sh. Run on a timer (see
# remoterig-update.timer). The Pi pulls; nothing pushes into the closed net.
#
# Config (env, or /opt/remoterig/update.env):
#   GITEA_BASE   default https://code.cubecraftcreations.com
#   REPO         default CubeCraft-Creations/remote-rig
#   GITEA_TOKEN  read token (required only if the repo is private)
#   DEPLOY_PATH  default /opt/remoterig/remoterig
#   SERVICE      default remoterig

set -euo pipefail

ENV_FILE="${ENV_FILE:-/opt/remoterig/update.env}"
# shellcheck disable=SC1090
[ -f "$ENV_FILE" ] && . "$ENV_FILE"

GITEA_BASE="${GITEA_BASE:-https://code.cubecraftcreations.com}"
REPO="${REPO:-CubeCraft-Creations/remote-rig}"
DEPLOY_DIR="/opt/remoterig"
DEPLOY_PATH="${DEPLOY_PATH:-$DEPLOY_DIR/remoterig}"
SERVICE="${SERVICE:-remoterig}"
TAG="dev"
DL="$GITEA_BASE/$REPO/releases/download/$TAG"
VERSION_FILE="$DEPLOY_DIR/VERSION"

AUTH=()
[ -n "${GITEA_TOKEN:-}" ] && AUTH=(-H "Authorization: token $GITEA_TOKEN")

log() { echo "[$(date -Is)] $*"; }

# 1. What version is published?
REMOTE_VER="$(curl -fsSL "${AUTH[@]}" "$DL/version.txt" | tr -d '[:space:]')" || {
    log "could not reach $DL/version.txt — skipping"; exit 0; }
[ -n "$REMOTE_VER" ] || { log "empty remote version — skipping"; exit 0; }

LOCAL_VER="$(cat "$VERSION_FILE" 2>/dev/null || echo none)"
if [ "$REMOTE_VER" = "$LOCAL_VER" ]; then
    log "up to date ($LOCAL_VER)"; exit 0
fi
log "update available: $LOCAL_VER -> $REMOTE_VER"

# 2. Download + verify checksum
TMP="$(mktemp -d)"; trap 'rm -rf "$TMP"' EXIT
curl -fsSL "${AUTH[@]}" "$DL/remoterig"        -o "$TMP/remoterig"
curl -fsSL "${AUTH[@]}" "$DL/remoterig.sha256" -o "$TMP/remoterig.sha256"
( cd "$TMP" && echo "$(cat remoterig.sha256)  remoterig" | sha256sum -c - ) || {
    log "checksum FAILED — aborting update"; exit 1; }

# 3. Deploy via the existing backup/restart/rollback logic
chmod +x "$TMP/remoterig"
"$DEPLOY_DIR/deploy.sh" "$TMP/remoterig" "$DEPLOY_PATH" "$SERVICE"

# 4. Record the installed version
echo "$REMOTE_VER" > "$VERSION_FILE"
log "updated to $REMOTE_VER"
