#!/bin/sh
#
# Copyright (c) 2026 Bryan C. Everly
# SPDX-License-Identifier: BSD-2-Clause
#
# restate hook: PostgreSQL, for capture --quiesce.
#
#   present NAME  whether PostgreSQL is on this host: prints present or absent
#   pause NAME    dump every database into $RESTATE_DUMP_DIR (pg_dumpall,
#                 gzipped as it is written), stop the units listed in
#                 /etc/restate/also.d/postgresql -- services that write to the
#                 database -- and then the cluster
#   resume NAME   start the cluster, then those units, again
#
# Or, with stop = never, nothing is stopped at all: pause takes the dump --
# pg_dumpall's one consistent snapshot, taken with everything running --
# and tells restate to leave the cluster's files out of the capture, since
# a copy of them made while it runs is of no use; resume has nothing to do.
#
# NAME is a Debian cluster's VERSION-NAME ("18-main"), whose unit is
# postgresql@18-main; anything else is stopped as the one unit "postgresql".
# The dump is the copy that survives a move to another major version, which
# the data directory alone does not; the stopped cluster's own files are a
# consistent copy without it. /etc/restate/postgresql.conf says when to dump:
#
#   dump = auto         (the default) dump unless the databases come to more
#                       than dump_limit; past that, the files alone
#   dump = always       dump, whatever the size
#   dump = never        never dump: the files alone
#   dump_limit = 10G    auto's limit, in bytes or with K, M, G or T
#   stop = always       (the default) stop the cluster while its files are
#                       copied, as above
#   stop = never        never stop it: the dump is taken whatever its size
#                       (dump_limit does not apply, and dump = never is
#                       refused, since it would leave nothing of the
#                       databases at all), written uncompressed as
#                       pg_dumpall.sql -- restate compresses what it stores,
#                       and keeps only the parts of a dump that changed since
#                       the last one, which a gzipped dump has none of -- and
#                       the cluster's own files are left out of the capture
#
# Any of these can be given for one capture instead, as
# --hook-option postgresql.KEY=VALUE (a job's hook_option), which is read
# over this file: a job can say stop = never for one server without that
# server's postgresql.conf saying so.
#
# A dump the dump directory has no room for -- the databases' size, as
# pg_database_size counts it, against what is free there -- is not begun.
# One that cannot be made leaves nothing of itself behind, and no dump of an
# earlier capture: the cluster is stopped all the same, its files copied as
# they are, and the pause fails so that the capture says it is incomplete.
#
# To change what this does, copy it to /etc/restate/hooks.d/postgresql (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 [ -d /usr/lib/postgresql ] || command -v postgres > /dev/null 2>&1 ||
    command -v pg_ctl > /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 any setting here is looked at or anything made.
case "$1" in
restored | paths) exit 2 ;;
esac

action=$1
name=$2
state=/run/restate/hooks
also=/etc/restate/also.d/postgresql
conf=/etc/restate/postgresql.conf

case "$name" in
[0-9]*-*) unit="postgresql@$name" cluster=$(printf '%s' "$name" | sed 's/-/\//') ;;
*) unit=postgresql cluster= ;;
esac
(umask 077 && mkdir -p "$state")
stopped="$state/postgresql-$(printf '%s' "$name" | tr -c 'A-Za-z0-9._-' '_')"

say() { echo "restate hook: postgresql $name: $*" >&2; }

# KEY's value: the capture's --hook-option postgresql.KEY=VALUE, the last one
# given, else $conf's ("KEY = VALUE", the last one given), else $2.
setting() {
  v=$(printf '%s\n' "${RESTATE_SETTINGS:-}" | sed -n "s/^$1=//p" | tail -n 1)
  if [ -z "$v" ] && [ -r "$conf" ]; then
    v=$(sed -n "s/^[[:space:]]*$1[[:space:]]*=[[:space:]]*//p" "$conf" |
      sed 's/[[:space:]]*\(#.*\)\{0,1\}$//' | tail -n 1)
  fi
  printf '%s\n' "${v:-$2}"
}

# Tells restate to leave the cluster's files out of this capture.
leave_out() {
  if [ -n "${RESTATE_REPLY:-}" ]; then
    echo leave-out > "$RESTATE_REPLY"
  fi
}

# SIZE (bytes, or a number with K, M, G or T) in bytes; nothing if it is not one.
bytes() {
  printf '%s\n' "$1" | awk '/^[0-9]+[KkMmGgTt]?$/ {
    n = $0 + 0; u = toupper(substr($0, length($0)))
    if (u == "K") n *= 1024; else if (u == "M") n *= 1048576
    else if (u == "G") n *= 1073741824; else if (u == "T") n *= 1099511627776
    printf "%.0f\n", n }'
}

# BYTES as GiB, for a person to read.
gib() { awk -v n="$1" 'BEGIN { printf "%.1f GiB\n", n / 1073741824 }'; }

# A PostgreSQL program, as postgres, for this cluster where Debian's wrapper
# picks one.
pg() {
  p=$1
  shift
  if [ -n "$cluster" ] && command -v pg_lsclusters > /dev/null 2>&1; then
    runuser -u postgres -- "$p" --cluster "$cluster" "$@"
  else
    runuser -u postgres -- "$p" "$@"
  fi
}

# Dump into the dump directory, or say why not. Called as "dump || ...", so
# set -e does not apply here: every step is checked.
dump() {
  # Uncompressed where nothing is stopped: see stop = never, above.
  if [ "$stop" = never ]; then
    out="$RESTATE_DUMP_DIR/pg_dumpall.sql"
  else
    out="$RESTATE_DUMP_DIR/pg_dumpall.sql.gz"
  fi
  tmp="$out.tmp"
  # A dump left from an earlier capture is not of this one, whichever kind
  # it was, and an earlier hook's part of one is no use to anyone.
  rm -f "$RESTATE_DUMP_DIR/pg_dumpall.sql.gz" "$RESTATE_DUMP_DIR/pg_dumpall.sql" \
    "$RESTATE_DUMP_DIR/pg_dumpall.sql.gz.tmp" "$RESTATE_DUMP_DIR/pg_dumpall.sql.tmp" \
    "$RESTATE_DUMP_DIR/pg_dumpall.sql.tmp.gz" || return 1
  mode=$(setting dump auto)
  limit=$(setting dump_limit 10G)
  case "$mode" in
  always | auto) ;;
  never)
    if [ "$stop" = never ]; then
      say "dump = never with stop = never would capture nothing of the databases:" \
        "refused; the cluster's files are left out"
      return 1
    fi
    say "dump = never in $conf: no pg_dumpall; the stopped cluster's files are copied"
    return 0
    ;;
  *)
    say "dump = $mode in $conf is not always, never or auto"
    return 1
    ;;
  esac
  max=$(bytes "$limit")
  if [ -z "$max" ]; then
    say "dump_limit = $limit in $conf is not a size"
    return 1
  fi
  size=$(pg psql -XAtq -d postgres \
    -c 'SELECT coalesce(sum(pg_database_size(oid)), 0) FROM pg_database' 2> /dev/null) ||
    size=
  case "$size" in
  '' | *[!0-9]*)
    say "could not ask the cluster its size: dumping without knowing it fits"
    size=
    ;;
  esac
  if [ -n "$size" ] && [ "$mode" = auto ] && [ "$stop" != never ] && [ "$size" -gt "$max" ]; then
    say "its databases come to $(gib "$size"), more than dump_limit ($limit): no pg_dumpall;" \
      "the stopped cluster's files are copied (dump = always in $conf dumps it anyway)"
    return 0
  fi
  free=$(df -Pk "$RESTATE_DUMP_DIR" | awk 'NR == 2 { printf "%.0f\n", $4 * 1024 }')
  case "$free" in
  '' | *[!0-9]*) ;;
  *)
    if [ -n "$size" ] && [ "$size" -gt "$free" ]; then
      say "no room for a pg_dumpall: its databases come to $(gib "$size"), and" \
        "$RESTATE_DUMP_DIR has $(gib "$free") free"
      return 1
    fi
    ;;
  esac
  # Whatever ends this, the part written goes.
  trap 'rm -f "$tmp"' EXIT
  trap 'exit 1' HUP INT TERM
  # Through gzip as it is written, so that the dump never needs its own size
  # uncompressed. The shell has no pipefail: each side says how it went.
  if [ "$stop" = never ]; then
    if pg pg_dumpall > "$tmp"; then how="pg_dumpall 0"; else how="pg_dumpall $?"; fi
  else
    how=$( {
      {
        pg pg_dumpall 3>&-
        echo "pg_dumpall $?" >&3
      } | gzip -c > "$tmp" 3>&- || echo "gzip failed" >&3
    } 3>&1)
  fi
  if [ "$how" != "pg_dumpall 0" ]; then
    rm -f "$tmp"
    say "the pg_dumpall did not finish ($(printf '%s' "$how" | tr '\n' ' ' | sed 's/ $//')):" \
      "nothing of it is kept"
    return 1
  fi
  mv -f "$tmp" "$out" || return 1
  trap - EXIT HUP INT TERM
}

stop=$(setting stop always)
case "$stop" in
always | never) ;;
*)
  say "stop = $stop is not always or never"
  exit 1
  ;;
esac

case "$action" in
pause)
  if [ "$stop" = never ]; then
    # The files are left out whatever happens: copied while the cluster
    # runs, they are no copy of it, and the capture is incomplete without a
    # dump to stand in for them.
    leave_out
    if [ -z "${RESTATE_DUMP_DIR:-}" ]; then
      say "stop = never, and no dump directory to dump into: nothing of it is captured"
      exit 1
    fi
    if ! dump; then
      say "stop = never, and no pg_dumpall: nothing of it is captured"
      exit 1
    fi
    exit 0
  fi
  failed=
  if [ -n "${RESTATE_DUMP_DIR:-}" ]; then
    dump || failed=1
  fi
  : > "$stopped"
  if [ -r "$also" ]; then
    grep -v '^[[:space:]]*\(#\|$\)' "$also" | while read -r u; do
      if systemctl is-active --quiet "$u"; then
        systemctl stop "$u" && printf '%s\n' "$u" >> "$stopped"
      fi
    done
  fi
  systemctl stop "$unit"
  if [ -n "$failed" ]; then
    say "stopped, and its files are copied as they are, with no pg_dumpall beside them"
    exit 1
  fi
  ;;
resume)
  # Nothing was stopped.
  if [ "$stop" = never ]; then
    exit 0
  fi
  systemctl start "$unit"
  if [ -r "$stopped" ]; then
    while read -r u; do
      systemctl start "$u" || echo "restate hook: $u did not start" >&2
    done < "$stopped"
    rm -f "$stopped"
  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
