#!/bin/sh
#
# Copyright (c) 2026 Bryan C. Everly
# SPDX-License-Identifier: BSD-2-Clause
#
# restate hook: a libvirt VM, for capture --quiesce.
#
#   present NAME  whether libvirt is on this host: prints present or absent
#   pause NAME    suspend the VM: its CPUs stop, so its disks stop changing
#   resume NAME   resume it -- unless it was already paused before, or
#                 something else has resumed it since
#
# A VM of a user's own (qemu:///session, which virt-manager and GNOME Boxes
# use) is suspended as that user, through their own libvirt; one of the
# system's through qemu:///system -- RESTATE_UID is 0 for one of those,
# though its QEMU runs as libvirt-qemu or qemu. A suspended VM's disks are as they would be
# after a sudden power cut: a journaling filesystem inside recovers.
#
# To change what this does, copy it to /etc/restate/hooks.d/libvirt (root's,
# mode 0755) and edit the copy: that one is used in place of this.
set -eu

# Before anything is made: present only looks.
if [ "$1" = present ]; then
  if command -v virsh > /dev/null 2>&1; then
    echo present
  else
    echo absent
  fi
  exit 0
fi

# Nothing to do after a restore, or before a walk: exit 2 says so, quietly,
# before anything is made.
case "$1" in
restored | paths) exit 2 ;;
esac

action=$1
name=$2
state=/run/restate/hooks
(umask 077 && mkdir -p "$state")
mark="$state/libvirt-${RESTATE_UID:-0}-$(printf '%s' "$name" | tr -c 'A-Za-z0-9._-' '_')"

virsh_as() {
  if [ "${RESTATE_UID:-0}" = 0 ]; then
    virsh -q -c qemu:///system "$@"
  else
    runuser -u "$RESTATE_USER" -- env XDG_RUNTIME_DIR="/run/user/$RESTATE_UID" \
      virsh -q -c qemu:///session "$@"
  fi
}

case "$action" in
pause)
  rm -f "$mark"
  # Apart, so that virsh failing fails this, rather than looking like a VM
  # that is not running.
  now=$(virsh_as domstate "$name")
  if [ "$now" = running ]; then
    virsh_as suspend "$name" > /dev/null
    : > "$mark"
  fi
  ;;
resume)
  if [ -e "$mark" ]; then
    rm -f "$mark"
    # Something else -- virt-manager, vagrant up -- may have resumed it
    # already, while its disks were being copied.
    now=$(virsh_as domstate "$name")
    if [ "$now" = paused ]; then
      virsh_as resume "$name" > /dev/null
    else
      echo "restate: the VM $name was $now before restate resumed it: something" \
        "else resumed it while its disks were copied, so they may not be consistent" >&2
    fi
  fi
  ;;
restored | paths)
  # Asked of every hook, after a restore and before a walk: nothing to do
  # for either here, which exit 2 says without a word.
  exit 2
  ;;
*)
  echo "usage: $0 present|pause|resume NAME" >&2
  exit 2
  ;;
esac
