# WHP LUKS state helpers — shared between setup.sh, boot-orchestrator.sh,
# whp-unlock-data-drive, whp-luks-unlock-helper.sh, and luks-header-backup.sh.
# Source this file:  . /path/to/lib-luks-state.sh
#
# Public API (POSIX-shell compatible):
#   luks_is_enabled       returns 0 if LUKS was provisioned on this server
#   luks_is_unlocked      returns 0 if /docker is on the expected dm-crypt mapper
#   luks_locked_reason    echoes a human-readable reason (empty if unlocked or disabled)
#
# The functions read /etc/whp/luks.conf. Override the path via LUKS_CONF_PATH
# env var for testing. Sourcing luks.conf sets these vars in the caller's
# shell — names are prefixed with LUKS_ to avoid collisions:
#   LUKS_ENABLED          0|1
#   LUKS_BACKING_DEVICE   e.g. /dev/sdb
#   LUKS_MAPPER_NAME      e.g. docker-crypt
#   LUKS_MOUNT_POINT      e.g. /docker

: "${LUKS_CONF_PATH:=/etc/whp/luks.conf}"

_luks_load_conf() {
    [ -f "$LUKS_CONF_PATH" ] || return 1
    # luks.conf is root-owned plain KEY=VALUE; safe to source.
    # shellcheck disable=SC1090
    . "$LUKS_CONF_PATH"
}

luks_is_enabled() {
    _luks_load_conf || return 1
    [ "${LUKS_ENABLED:-0}" = "1" ]
}

luks_is_unlocked() {
    luks_is_enabled || return 1
    _luks_source=$(findmnt -no SOURCE "${LUKS_MOUNT_POINT:-/docker}" 2>/dev/null) || return 1
    [ "$_luks_source" = "/dev/mapper/${LUKS_MAPPER_NAME:-docker-crypt}" ]
}

luks_locked_reason() {
    luks_is_enabled || { echo ""; return 0; }
    _luks_mp="${LUKS_MOUNT_POINT:-/docker}"
    _luks_expected="/dev/mapper/${LUKS_MAPPER_NAME:-docker-crypt}"
    if ! mountpoint -q "$_luks_mp" 2>/dev/null; then
        echo "$_luks_mp is not mounted"
        return 0
    fi
    _luks_source=$(findmnt -no SOURCE "$_luks_mp" 2>/dev/null)
    if [ "$_luks_source" != "$_luks_expected" ]; then
        echo "$_luks_mp is mounted on $_luks_source instead of $_luks_expected"
        return 0
    fi
    echo ""
}
