#!/bin/sh
# Copyright: 2026 Aitor <aitor@genuen.org>
# License: CC0-1.0
#
# Called from s6-rc-policy rc.shutdown.final (s6-linux-init stage 4,
# after SIGKILL + umountall). Must NOT use s6-rc: the live state is gone.
# Close remaining crypttab mappings the same way as cryptdisks-stop /
# cryptdisks-early-stop oneshots. Never block HPR.
#
# cryptsetup may be installed with no encryption in use: exit immediately
# if there is nothing to close.

exec 2>&1

ebegin() { [ "${VERBOSE:-}" = no ] || echo "$@"; }
eend() { r=${1:-0}; shift || true; [ "$r" -eq 0 ] || [ "${VERBOSE:-}" = no ] || echo "$*" >&2; return 0; }
einfo() { [ "${VERBOSE:-}" = no ] || echo "$@"; }
ewarn() { echo "$@" >&2; }
eerror() { echo "$@" >&2; }

[ -r /lib/cryptsetup/cryptdisks-functions ] || exit 0

_save_path="$PATH"
# shellcheck disable=SC1091
. /lib/cryptsetup/cryptdisks-functions
PATH="$_save_path"
export PATH

case "$CRYPTDISKS_ENABLE" in
	[Nn]*) exit 0 ;;
esac

# Package present ≠ encryption in use.
[ -s "$TABFILE" ] || exit 0
# No open CRYPT mappings → nothing for do_stop to do.
if ! dmsetup ls --target crypt 2>/dev/null | grep -q .; then
	exit 0
fi

DEFAULT_LOUD="yes"
INITSTATE="remaining"
do_stop || true

DEFAULT_LOUD=""
INITSTATE="early"
do_stop || true

exit 0
