#!/bin/sh
# Update the vibe-live appliance to a newer release, in one command (F111).
#
#     ./update-lxc-appliance.sh 200                 # the newest release
#     ./update-lxc-appliance.sh 200 0.58.0          # that release
#     ./update-lxc-appliance.sh 200 ./my.tar.zst    # a template you built
#
# Run ON the Proxmox host, as root. The owner, 2026-10-16: "How would lxc
# update? Could we prebuild the all-in-one image for them?" -- CI publishes
# each release's template (scripts/ci-lxc-template.sh), so no podman is
# needed anywhere.
#
# What it does, and why in this order:
#   1. fetches the template and checks its sha256;
#   2. creates a NEW container from it with the old one's settings -- its
#      cores, memory, network and address, and the lxc.* lines that carry
#      the secrets and the init;
#   3. stops the old one and moves its /data volume to the new one
#      (`pct move-volume`): the database, its key's work and the recordings
#      never get copied, and the system around them is simply new. An
#      appliance made before /data had a volume of its own has its /data
#      copied into one;
#   4. starts the new one and waits for /livez -- the database migrates at
#      start. If it never answers, the volume goes back and the old one
#      starts again, as it was;
#   5. keeps the old one, stopped and not started at boot, for a rollback.
#      Remove it once you are happy: `pct destroy <old ctid>`.
#
# The container's ID changes (the new one takes the next free ID); its
# address does not, since the network settings are carried over.
set -eu

OLD="${1:-}"
WANT="${2:-}"
# Where the releases' templates are published (the same forge as the image).
TEMPLATES="${TEMPLATES:-https://forgejo.gmatte.xyz/api/packages/gmatte/generic/vibe-live-lxc}"
CACHE="${CACHE:-/var/lib/vz/template/cache}"

if [ -z "$OLD" ]; then
	echo "usage: $0 <ctid> [version | template.tar.zst]" >&2
	exit 1
fi
command -v pct >/dev/null 2>&1 || { echo "pct not found: run this on the Proxmox host." >&2; exit 1; }
pct status "$OLD" >/dev/null 2>&1 || { echo "No container $OLD." >&2; exit 1; }
conf="/etc/pve/lxc/${OLD}.conf"
grep -q '^lxc.init.cmd' "$conf" || { echo "CT $OLD was not made by create-lxc-appliance.sh (no lxc.init.cmd)." >&2; exit 1; }

# --- 1. the template ---------------------------------------------------
if [ -f "$WANT" ]; then
	template=$WANT
else
	version=${WANT:-$(curl -fsS "$TEMPLATES/latest/version" | tr -d '[:space:]')}
	[ -n "$version" ] || { echo "Could not learn the newest release from $TEMPLATES." >&2; exit 1; }
	template="$CACHE/vibe-live-$version.tar.zst"
	if [ ! -f "$template" ]; then
		echo "==> fetching the $version template"
		curl -fL --progress-bar -o "$template.partial" "$TEMPLATES/$version/vibe-live-$version.tar.zst"
		want=$(curl -fsS "$TEMPLATES/$version/vibe-live-$version.tar.zst.sha256" | cut -d' ' -f1)
		got=$(sha256sum "$template.partial" | cut -d' ' -f1)
		[ "$want" = "$got" ] || { rm -f "$template.partial"; echo "The $version template does not match its sha256." >&2; exit 1; }
		mv "$template.partial" "$template"
	fi
fi

# --- 2. the new container, with the old one's settings ------------------
get() { pct config "$OLD" | sed -n "s/^$1: //p"; }
rootfs=$(get rootfs)
storage=${rootfs%%:*}
size=$(printf '%s' "$rootfs" | sed -n 's/.*size=\([0-9]*\)G.*/\1/p')
NEW=$(pvesh get /cluster/nextid)
echo "==> creating CT $NEW from $(basename "$template") with CT $OLD's settings"
pct create "$NEW" "$template" \
	--hostname "$(get hostname)" \
	--cores "$(get cores)" \
	--memory "$(get memory)" \
	--swap "$(get swap)" \
	--rootfs "${storage}:${size:-8}" \
	--net0 "$(get net0)" \
	--unprivileged 1
# The secrets, the init and the network LXC raises: create-lxc-appliance.sh's
# lxc.* lines, as they are.
grep '^lxc\.' "$conf" >> "/etc/pve/lxc/${NEW}.conf"

# --- 3. the data ---------------------------------------------------------
echo "==> stopping CT $OLD and moving its data to CT $NEW"
pct stop "$OLD" 2>/dev/null || true
moved=no
if [ -n "$(get mp0)" ]; then
	pct move-volume "$OLD" mp0 --target-vmid "$NEW" --target-volume mp0
	moved=yes
else
	# Made before /data had a volume of its own: copied into a new one.
	pct set "$NEW" --mp0 "${storage}:${DATA_GB:-20},mp=/data"
	pct mount "$OLD" >/dev/null
	pct mount "$NEW" >/dev/null
	cp -a "/var/lib/lxc/$OLD/rootfs/data/." "/var/lib/lxc/$NEW/rootfs/data/"
	chown --reference="/var/lib/lxc/$OLD/rootfs/data" "/var/lib/lxc/$NEW/rootfs/data"
	pct unmount "$NEW"
	pct unmount "$OLD"
fi

# --- 4. start it, or put everything back ---------------------------------
echo "==> starting CT $NEW"
pct start "$NEW"
i=0
until pct exec "$NEW" -- curl -fsS -o /dev/null http://127.0.0.1:8080/livez 2>/dev/null; do
	i=$((i + 1))
	if [ "$i" -ge 60 ]; then
		echo "CT $NEW never answered /livez; putting CT $OLD back as it was." >&2
		pct stop "$NEW" 2>/dev/null || true
		if [ "$moved" = yes ]; then
			pct move-volume "$NEW" mp0 --target-vmid "$OLD" --target-volume mp0
		fi
		pct start "$OLD"
		echo "CT $OLD is running again; CT $NEW is left stopped to look at (pct console $NEW)." >&2
		exit 1
	fi
	sleep 2
done

# --- 5. keep the old one for a rollback ----------------------------------
pct set "$NEW" --onboot 1
pct set "$OLD" --onboot 0
version=$(pct exec "$NEW" -- curl -fsS http://127.0.0.1:8080/api/v1/instance 2>/dev/null | sed -n 's/.*"version":"\([^"]*\)".*/\1/p')

cat <<DONE

CT $NEW is up, running vibe-live ${version:-(version unknown)}, with CT $OLD's data and address.

CT $OLD is stopped and kept, for a rollback:

  pct stop $NEW && pct move-volume $NEW mp0 --target-vmid $OLD --target-volume mp0 && pct start $OLD

Once you are happy with $NEW, remove it:

  pct destroy $OLD

DONE
