#!/usr/bin/env bash
# vault — mount/dismount VeraCrypt containers with automatic mountpoint creation and cleanup
# now suppresses PIM, keyfile, and hidden‐volume prompts by default
# Usage: vault {open|close} /full/path/to/container.hc

set -euo pipefail

usage() {
  echo "Usage: $0 {open|close} /full/path/to/container.hc"
  exit 1
}

[[ $# -eq 2 ]] || usage
action=$1
rawpath=$2

container=$(eval echo "$rawpath")
[[ -f "$container" ]] || { echo "Container not found: $container"; exit 1; }

# derive mountpoint
base=$(basename "$container")
name="${base%.*}"
mountpoint="/mnt/$name"

require_sudo() {
  if (( EUID != 0 )); then
    exec sudo bash "$0" "$action" "$rawpath"
  fi
}

case "$action" in
  open)
    if mountpoint -q "$mountpoint"; then
      echo "Already mounted at $mountpoint"
      exit 0
    fi

    require_sudo
    mkdir -p "$mountpoint"
    veracrypt -t \
      --keyfiles="" \
      --pim=0 \
      --protect-hidden=no \
      --mount "$container" "$mountpoint"
    echo "Mounted $container → $mountpoint"
    ;;

  close)
    require_sudo
    # dismount and suppress warnings
    veracrypt -t --dismount "$mountpoint" || true
    # cleanup empty dir
    if [[ -d "$mountpoint" ]]; then
      rmdir "$mountpoint" && echo "Removed mountpoint $mountpoint"
    fi
    ;;

  *)
    usage
    ;;
esac
