#!/bin/sh
set -euo pipefail

MAPPER_NAME="host_vars_crypt"
MOUNT_POINT="/app/host_vars"

# Unmount if mounted
if mountpoint -q "$MOUNT_POINT"; then
    echo "Unmounting $MOUNT_POINT..."
    umount "$MOUNT_POINT"
else
    echo "$MOUNT_POINT is not mounted."
fi



if cryptsetup status "$MAPPER_NAME" >/dev/null 2>&1; then
    echo "Closing stale mapping $MAPPER_NAME..."
    if ! cryptsetup close "$MAPPER_NAME"; then
        echo "cryptsetup close failed, forcing dmsetup remove..."
        dmsetup remove --force --retry "$MAPPER_NAME" || true
    fi
fi


# Close the LUKS/dm-crypt device if open
if [ -e "/dev/mapper/$MAPPER_NAME" ]; then
    echo "Closing /dev/mapper/$MAPPER_NAME..."
    cryptsetup close "$MAPPER_NAME"
else
    echo "Mapper $MAPPER_NAME is not active."
fi

echo "Vault is now closed."

