#!/bin/sh
#
# Copyright (c) 2026 Bryan C. Everly
# SPDX-License-Identifier: BSD-2-Clause
#
# restate hook: Docker's containers, for capture --quiesce.
#
#   present NAME  whether Docker is on this host: prints present or absent
#   pause NAME    pause every running container, so their volumes stop
#                 changing
#   resume NAME   unpause the ones it paused
#
# To change what this does, copy it to /etc/restate/hooks.d/docker (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 docker > /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

state=/run/restate/hooks
(umask 077 && mkdir -p "$state")
paused="$state/docker"

case "$1" in
pause)
  docker ps --quiet --filter status=running > "$paused"
  if [ -s "$paused" ]; then
    # One id to a line: word splitting is what is wanted here.
    # shellcheck disable=SC2046
    docker pause $(cat "$paused") > /dev/null
  fi
  ;;
resume)
  if [ -s "$paused" ]; then
    # shellcheck disable=SC2046
    docker unpause $(cat "$paused") > /dev/null
  fi
  rm -f "$paused"
  ;;
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
