#!/bin/sh

CONTAINER=${2:-"$HOME/vault.hc"}

BASENAME=$(basename "$CONTAINER")
MAPPER_NAME="${BASENAME%.*}"
MOUNT_POINT="/mnt/$MAPPER_NAME"

case "$1" in
  open)
    if [ ! -f "$CONTAINER" ]; then
      echo "Container not found: $CONTAINER"
      exit 1
    fi

    if [ -e "/dev/mapper/$MAPPER_NAME" ]; then
      echo "Already opened at /dev/mapper/$MAPPER_NAME"
      exit 1
    fi

    mkdir -p "$MOUNT_POINT" || exit 1

    if sudo cryptsetup open --type tcrypt "$CONTAINER" "$MAPPER_NAME"; then
      sudo mount "/dev/mapper/$MAPPER_NAME" "$MOUNT_POINT" &&
      echo "Mounted at $MOUNT_POINT"
    else
      echo "Failed to open container."
      exit 1
    fi
    ;;

  close)
    if mountpoint -q "$MOUNT_POINT"; then
      sudo umount "$MOUNT_POINT"
    fi

    if [ -e "/dev/mapper/$MAPPER_NAME" ]; then
      sudo cryptsetup close "$MAPPER_NAME"
      echo "Closed and unmounted $MOUNT_POINT."
    else
      echo "Container is not open."
    fi
    ;;

  *)
    echo "Usage: $0 {open|close} [path/to/container.hc]"
    exit 1
    ;;
esac

