#!/bin/bash
# UPS emergency shutdown - cleanly stop services and export ZFS before poweroff
# Called by NUT upsmon when UPS battery is critical

LOG="/var/log/server-admin/ups-shutdown.log"

log() {
    echo "[$(date '+%Y-%m-%d %H:%M:%S')] $*" >> "$LOG"
}

log "=========================================="
log "UPS SHUTDOWN INITIATED"
log "=========================================="

# Phase 1: Stop services that depend on /mnt/storage
log "Phase 1: Stopping storage-dependent services..."

STORAGE_SERVICES=(
    plexmediaserver.service
    smb.service
    kavita.service
    bazarr-anime.service
    bazarr.service
    php-fpm.service
    notify_push.service
    tautulli.service
    oxyromon-server.service
    kometa.service
    seerr.service
)

for svc in "${STORAGE_SERVICES[@]}"; do
    if systemctl is-active --quiet "$svc" 2>/dev/null; then
        log "  Stopping $svc"
        systemctl stop "$svc" --no-block 2>/dev/null &
    fi
done

# Wait for storage services to stop (max 15s)
log "  Waiting for services to stop (max 15s)..."
DEADLINE=$((SECONDS + 15))
for svc in "${STORAGE_SERVICES[@]}"; do
    while systemctl is-active --quiet "$svc" 2>/dev/null && [[ $SECONDS -lt $DEADLINE ]]; do
        sleep 1
    done
done
log "  Storage services stopped"

# Phase 2: Save VMs (suspend to disk for fast recovery)
log "Phase 2: Saving VMs..."
for vm in $(virsh list --name --state-running 2>/dev/null); do
    log "  Saving VM: $vm"
    virsh managedsave "$vm" --bypass-cache 2>> "$LOG" &
done
wait
log "  VMs saved"

# Phase 3: Export ZFS pool
log "Phase 3: Exporting ZFS pool..."

# Lazy unmount anything still holding the pool
umount -l /mnt/storage 2>/dev/null

# Export the pool
if zpool export storage 2>> "$LOG"; then
    log "  ZFS pool exported cleanly"
else
    log "  WARNING: ZFS pool export failed, forcing..."
    zpool export -f storage 2>> "$LOG" || log "  ERROR: Force export also failed"
fi

# Phase 4: Power off
log "Phase 4: Powering off"
log "=========================================="

/sbin/shutdown -h +0
