#!/bin/bash

# Script to configure automatic mounting of a USB drive on Raspberry Pi OS Lite

# --- Configuration ---
MOUNT_POINT="/mnt/usb"  # Desired mount point
FILESYSTEM_TYPE="auto"   # Filesystem type (auto, vfat, ntfs-3g, ext4, etc.)
MOUNT_OPTIONS="defaults,nofail,uid=pi,gid=pi,umask=007" # Mount options
# --- End Configuration ---

# Check if the user is root
if [[ "$EUID" -ne 0 ]]; then
  echo "This script must be run with sudo."
  exit 1
fi

# Ensure the mount point directory exists
if [ ! -d "$MOUNT_POINT" ]; then
  echo "Creating mount point directory: $MOUNT_POINT"
  sudo mkdir -p "$MOUNT_POINT"
fi

# Get the UUID of the USB drive
echo "Please plug in the USB drive you want to auto-mount and press Enter."
read

echo "Identifying USB drive..."
USB_DEVICE=$(sudo blkid | grep -oE '^/dev/sd[a-z][0-9]*:' | sed 's/://')

if [ -z "$USB_DEVICE" ]; then
  echo "Error: Could not identify the USB drive. Please ensure it is plugged in."
  exit 1
fi

USB_UUID=$(sudo blkid "$USB_DEVICE" | grep -oE 'UUID="[^"]+"' | sed 's/UUID="//' | sed 's/"//')

if [ -z "$USB_UUID" ]; then
  echo "Error: Could not retrieve the UUID of the USB drive."
  exit 1
fi

echo "Found USB drive: $USB_DEVICE with UUID: $USB_UUID"

# Check if the entry already exists in /etc/fstab
if grep -q "^UUID=\"$USB_UUID\"" /etc/fstab; then
  echo "Entry for this USB drive already exists in /etc/fstab."
  read -p "Do you want to overwrite the existing entry? (y/N) " -n 1 -r
  echo    # Move to a new line after the user's response
  if [[ ! "$REPLY" =~ ^[Yy]$ ]]; then
    echo "Skipping /etc/fstab modification."
    exit 0
  fi
  # Remove the existing entry
  sudo sed -i "/^UUID=\"$USB_UUID\"/d" /etc/fstab
fi

# Add the new entry to /etc/fstab
echo "Adding entry to /etc/fstab..."
echo "UUID=\"$USB_UUID\" $MOUNT_POINT $FILESYSTEM_TYPE $MOUNT_OPTIONS 0 0" | sudo tee -a /etc/fstab

if [ $? -eq 0 ]; then
  echo "Successfully added the following line to /etc/fstab:"
  echo "UUID=\"$USB_UUID\" $MOUNT_POINT $FILESYSTEM_TYPE $MOUNT_OPTIONS 0 0"
  echo "The USB drive will now be automatically mounted at '$MOUNT_POINT' on boot."
  echo "You can try mounting it now with: sudo mount $MOUNT_POINT"
else
  echo "Error: Failed to add the entry to /etc/fstab."
  echo "Please check /etc/fstab for any errors."
fi

exit 0
