#!/bin/sh
#
# Copyright (c) 2026 Bryan C. Everly
# SPDX-License-Identifier: BSD-2-Clause
#
# restate hook: an LXD container, for capture --quiesce.
#
#   present NAME  whether LXD is on this host: prints present or absent
#   pause NAME    freeze the container (lxc pause): its processes stop where
#                 they are, so its files stop changing
#   resume NAME   thaw it again -- unless it was frozen before
#
# To change what this does, copy it to /etc/restate/hooks.d/lxd (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 lxc > /dev/null 2>&1 && { [ -d /var/snap/lxd ] || [ -d /var/lib/lxd ]; }; 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/lxd-$(printf '%s' "$name" | tr -c 'A-Za-z0-9._-' '_')"

case "$action" in
pause)
  rm -f "$mark"
  if [ "$(lxc list "$name" --columns s --format csv)" = RUNNING ]; then
    lxc pause "$name"
    : > "$mark"
  fi
  ;;
resume)
  if [ -e "$mark" ]; then
    lxc start "$name"
    rm -f "$mark"
  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
