#!/usr/bin/env bash
# On the Proxmox host (not in the VM): records the newest vzdump of VM103 for the driver's backup_check.
# The VM cannot see Proxmox storage, so this writes a small JSON file into it through the guest agent:
#   {"vmid":103,"storage":"vm-storage","latest":{"volid":"…","ctime":<epoch s>}|null,"checked_at":"<UTC>"}
# Installed as /usr/local/sbin/homelab-upgrade-vzdump-record, run hourly by homelab-upgrade-vzdump.timer (docs/DEPLOY.md).
# Reads storage metadata only; the one write is that file on the VM (written aside, then renamed).
set -euo pipefail

vmid=${VMID:-103}
storage=${STORAGE:-vm-storage}
target=/srv/appdata/homelab-upgrade/host/vzdump.json

record=$(pvesh get "/nodes/$(hostname)/storage/$storage/content" --vmid "$vmid" --content backup --output-format json |
  VMID="$vmid" STORAGE="$storage" python3 -c '
import datetime, json, os, sys
vmid = int(os.environ["VMID"])
rows = [r for r in json.load(sys.stdin) if r.get("vmid") == vmid and isinstance(r.get("ctime"), int) and r.get("volid")]
latest = max(rows, key=lambda r: r["ctime"], default=None)
print(json.dumps({
    "vmid": vmid,
    "storage": os.environ["STORAGE"],
    "latest": None if latest is None else {"volid": latest["volid"], "ctime": latest["ctime"]},
    "checked_at": datetime.datetime.now(datetime.timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ"),
}, separators=(",", ":")))')

reply=$(printf '%s\n' "$record" | qm guest exec "$vmid" --pass-stdin 1 --timeout 30 -- \
  /bin/sh -c "umask 022 && cat > $target.tmp && mv $target.tmp $target")
# qm prints the guest's result as JSON and exits 0 even when the command in the guest failed.
exitcode=$(printf '%s' "$reply" | python3 -c 'import json, sys; print(json.load(sys.stdin).get("exitcode", 1))')
if [[ "$exitcode" != 0 ]]; then
  echo "writing $target in VM $vmid failed (exit $exitcode)" >&2
  exit 1
fi
echo "recorded: $record"
