#!/bin/bash

if [ -e "/etc/bigmountall-no" ]; then
   exit 0
fi

# Compatibility symlinks (independent of each other)
if [ ! -e "/media" ]; then
   ln -s /mnt /media
fi
if [ ! -e "/mnt/user-mount" ] && [ -d /run/media ]; then
   ln -s /run/media /mnt/user-mount
fi

# Change space delimiters to newline
OIFS=$IFS
IFS=$'\n'

# Detect last logged-in user across display managers, fallback to first human UID
UserLastLogin=""
if [ -r /var/lib/sddm/state.conf ]; then
   UserLastLogin="$(grep '^User=' /var/lib/sddm/state.conf | cut -f2- -d= | sed 's| *$||')"
fi
if [ -z "$UserLastLogin" ] && [ -r /var/lib/lightdm/data/last-user ]; then
   UserLastLogin="$(head -n1 /var/lib/lightdm/data/last-user)"
fi
if [ -z "$UserLastLogin" ]; then
   UserLastLogin="$(getent passwd | awk -F: '$3 >= 1000 && $3 < 60000 { print $1; exit }')"
fi

if [ -n "$UserLastLogin" ] && id -u "$UserLastLogin" >/dev/null 2>&1; then
   UserID=$(id -u "$UserLastLogin")
   GroupID=$(id -g "$UserLastLogin")
else
   UserID=1000
   GroupID=1000
fi

# Iterate partitions, skip swap and squashfs
for i in $(blkid | grep -v -e 'TYPE="swap"' -e 'TYPE="squashfs"'); do

   PARTITION="$(echo "$i" | sed 's|:.*||;s|.*/||')"

   # Parent block device works for sdX, nvmeXnYpZ, mmcblkXpY
   PARENT_DEV="$(lsblk -no PKNAME "/dev/$PARTITION" 2>/dev/null | head -n1)"
   if [ -z "$PARENT_DEV" ]; then
      PARENT_DEV="$PARTITION"
   fi

   LABEL_NAME=""

   # 1. Try LABEL (not PARTLABEL)
   LABEL_NAME=$(echo "$i" | sed -n 's/.* LABEL="\([^"]*\)".*/\1/p')
   if [ -z "$LABEL_NAME" ]; then
      LABEL_NAME=$(echo "$i" | sed -n 's/^[^:]*: LABEL="\([^"]*\)".*/\1/p')
   fi

   # 2. Fall back to PARTLABEL
   if [ -z "$LABEL_NAME" ]; then
      LABEL_NAME=$(echo "$i" | sed -n 's/.*PARTLABEL="\([^"]*\)".*/\1/p')
   fi

   # 3. Sanitize label (avoid spaces and slashes in path)
   LABEL_NAME=$(echo "$LABEL_NAME" | tr ' /' '__')

   # 4. Resolve a free mount point with numeric suffix on collision
   if [ -n "$LABEL_NAME" ]; then
      BASE_NAME="$LABEL_NAME"
      COUNTER=1
      while : ; do

         # Remove stale symlink before existence check
         if [ -L "/mnt/$LABEL_NAME" ]; then
            rm "/mnt/$LABEL_NAME"
         fi

         if [ ! -e "/mnt/$LABEL_NAME" ]; then
            break
         fi

         # Folder exists but nothing is mounted on it (stale) — reuse
         IS_MOUNTED=$(grep -F " /mnt/$LABEL_NAME " /proc/mounts)
         if [ -z "$IS_MOUNTED" ]; then
            break
         fi

         # Already mounted by this exact device — idempotent success
         if grep -qF "/dev/$PARTITION /mnt/$LABEL_NAME " /proc/mounts; then
            break
         fi

         # Collision with another device — increment suffix
         LABEL_NAME="${BASE_NAME}${COUNTER}"
         ((COUNTER++))
      done

      MOUNT_POINT="/mnt/$LABEL_NAME"
   else
      MOUNT_POINT="/mnt/$PARTITION"
   fi

   bigremovable=n

   # Removable flag in sysfs
   if [ -r "/sys/block/$PARENT_DEV/removable" ] && [ "$(cat "/sys/block/$PARENT_DEV/removable")" = "1" ]; then
      bigremovable=y
   fi

   # USB transport
   if udisksctl info -b "/dev/$PARENT_DEV" 2>/dev/null | grep -q -- "-usb-"; then
      bigremovable=y
   fi

   # HintIgnore
   if udisksctl info -b "/dev/$PARTITION" 2>/dev/null | grep -q "HintIgnore:.*true"; then
      bigremovable=y
   fi

   # Already mounted (exact device match — trailing space avoids prefix matches)
   if grep -qE "^/dev/${PARTITION} " /proc/mounts; then
      bigremovable=y
   fi

   if [ "$bigremovable" = "n" ]; then

      mkdir -p "$MOUNT_POINT"

      mount_rc=1
      if echo "$i" | grep -q 'TYPE="ntfs"'; then
         ntfsfix "/dev/$PARTITION"
         mount -t lowntfs-3g -o "uid=$UserID,gid=$GroupID,rw,noatime,exec,umask=000,nodev,nofail,x-gvfs-show" "/dev/$PARTITION" "$MOUNT_POINT"
         mount_rc=$?
      elif echo "$i" | grep -q 'TYPE=".*fat.*"'; then
         mount -o "uid=$UserID,gid=$GroupID,noatime,rw,umask=000,nodev,nofail,x-gvfs-show" "/dev/$PARTITION" "$MOUNT_POINT"
         mount_rc=$?
      else
         mount -o "noatime,rw,nodev,nofail,x-gvfs-show" "/dev/$PARTITION" "$MOUNT_POINT"
         mount_rc=$?
      fi

      # Reverse symlink only on successful mount and when paths differ
      if [ "$mount_rc" -eq 0 ] && [ -n "$LABEL_NAME" ] && [ "$MOUNT_POINT" != "/mnt/$PARTITION" ] && [ ! -e "/mnt/$PARTITION" ]; then
         ln -s "$MOUNT_POINT" "/mnt/$PARTITION" 2>/dev/null
      fi
   fi
done
IFS=$OIFS
