#!/bin/sh
set -euo pipefail

VAULT_FILE="/app/vault/host_vars.img"
MAPPER_NAME="host_vars_crypt"
MOUNT_POINT="/app/host_vars"
LOOP_DEVICE="/dev/loop50"

mkdir -p "$MOUNT_POINT"

# Always close if active
if cryptsetup status "$MAPPER_NAME" >/dev/null 2>&1; then
    echo "Closing stale mapping $MAPPER_NAME..."
    cryptsetup close "$MAPPER_NAME"
fi

# Detach loop device if already in use
if losetup "$LOOP_DEVICE" >/dev/null 2>&1; then
    echo "Detaching stale loop device $LOOP_DEVICE..."
    losetup -d "$LOOP_DEVICE"
fi

# Create loop device if missing
if [ ! -e "$LOOP_DEVICE" ]; then
    echo "Creating loop device $LOOP_DEVICE..."
    mknod "$LOOP_DEVICE" b 7 50
    chmod 660 "$LOOP_DEVICE"
fi

# Attach vault file to loop device
echo "Attaching $VAULT_FILE to $LOOP_DEVICE..."
losetup "$LOOP_DEVICE" "$VAULT_FILE"

# Open encrypted volume
echo "Opening encrypted volume..."
cryptsetup open "$LOOP_DEVICE" "$MAPPER_NAME"

# Format if needed
if ! blkid "/dev/mapper/$MAPPER_NAME" >/dev/null 2>&1; then
    echo "No filesystem found, creating ext4..."
    mkfs.ext4 "/dev/mapper/$MAPPER_NAME"
fi

# Mount
echo "Mounting at $MOUNT_POINT..."
mount "/dev/mapper/$MAPPER_NAME" "$MOUNT_POINT"

echo "Vault is mounted at $MOUNT_POINT"


