#!/bin/sh
set -euo pipefail

VAULT_DIR="/app/vault"
VAULT_FILE="$VAULT_DIR/host_vars.img"
MAPPER_NAME="host_vars_crypt"
MOUNT_POINT="/app/host_vars"
SIZE_MB=25

# Prepare directories
mkdir -p "$VAULT_DIR"
mkdir -p "$MOUNT_POINT"

# Create 5MB backing file if it doesn't exist
if [ ! -f "$VAULT_FILE" ]; then
    echo "Creating $SIZE_MB MB vault file at $VAULT_FILE"
    dd if=/dev/zero of="$VAULT_FILE" bs=1M count=$SIZE_MB
fi

# Setup LUKS encryption if not already formatted
if ! cryptsetup isLuks "$VAULT_FILE"; then
    echo "Formatting with LUKS (you will be prompted for a passphrase)..."
    cryptsetup luksFormat "$VAULT_FILE"
fi

# Open the encrypted volume
if ! [ -e "/dev/mapper/$MAPPER_NAME" ]; then
    echo "Opening encrypted volume..."
    cryptsetup open "$VAULT_FILE" "$MAPPER_NAME"
fi

# Create filesystem if not already present
if ! blkid /dev/mapper/"$MAPPER_NAME" >/dev/null 2>&1; then
    echo "Creating ext4 filesystem..."
    mkfs.ext4 /dev/mapper/"$MAPPER_NAME"
fi

# Mount it
if ! mountpoint -q "$MOUNT_POINT"; then
    echo "Mounting at $MOUNT_POINT"
    mount /dev/mapper/"$MAPPER_NAME" "$MOUNT_POINT"
fi

echo "Encrypted volume is ready and mounted at $MOUNT_POINT"

