#!/bin/bash
# NUT-triggered controlled shutdown for Proxmox nodes
# Place at /usr/local/bin/ups-shutdown.sh on each Proxmox node.
# chmod 755 /usr/local/bin/ups-shutdown.sh
#
# Called by upsmon SHUTDOWNCMD when FSD is received from NUT master.
# Stops all running VMs and CTs gracefully (60s timeout, then force),
# waits for all to complete, then powers off the node.

logger -t nut-shutdown "Starting controlled guest shutdown on $(hostname)"

# Stop all running VMs gracefully
for vmid in $(qm list --running 2>/dev/null | awk 'NR>1{print $1}'); do
    logger -t nut-shutdown "Stopping VM $vmid"
    qm shutdown "$vmid" --timeout 60 --forceStop 1 &
done

# Stop all running CTs gracefully
for ctid in $(pct list --running 2>/dev/null | awk 'NR>1{print $1}'); do
    logger -t nut-shutdown "Stopping CT $ctid"
    pct shutdown "$ctid" --timeout 60 --forceStop 1 &
done

# Wait for all guest shutdowns to complete
wait

logger -t nut-shutdown "All guests stopped, shutting down node $(hostname)"
sleep 3
shutdown -h now
