#!/usr/bin/env bash
#
# rackhelm-update — system launcher for the RackHelm updater.
#
# Installed to /usr/local/bin by install.sh and refreshed by every update.
# It does exactly one job: run a COPY of the current release's updater, so the
# script being executed is never the file being replaced (bash reads scripts
# incrementally; replacing a running script corrupts its own control flow).
#
set -euo pipefail

ROOT_LINK="${RACKHELM_ROOT:-/var/www/rackhelm}"

if [ "$(id -u)" != "0" ]; then
    echo "rackhelm-update must run as root:  sudo rackhelm-update $*" >&2
    exit 1
fi

UPDATER_DIR="$ROOT_LINK/updater"
if [ ! -f "$UPDATER_DIR/update.sh" ]; then
    echo "No updater found at $UPDATER_DIR." >&2
    echo "This installation predates the self-update mechanism. Follow the" >&2
    echo "'Updating RackHelm' guide in the documentation for the one-time" >&2
    echo "manual upgrade that installs it." >&2
    exit 1
fi

RUN_DIR="$(mktemp -d /tmp/rackhelm-update.XXXXXX)"
trap 'rm -rf "$RUN_DIR"' EXIT
cp -a "$UPDATER_DIR/update.sh" "$RUN_DIR/update.sh"

# A dropped SSH session mid-update is recoverable (--resume), but avoidable is
# better than recoverable.
if [ -t 0 ] && [ -z "${TMUX:-}" ] && [ -z "${STY:-}" ]; then
    echo "note: running outside tmux/screen — if this session drops mid-update," >&2
    echo "      continue with: sudo rackhelm-update --resume" >&2
fi

RH_UPDATER_DIR="$UPDATER_DIR" exec bash "$RUN_DIR/update.sh" "$@"
