#!/bin/sh
#
# Auto-mount script for /home/pi
# Called from udev rule when new storage device is inserted
# Mounts partitions by their LABEL (volume label) under /home/pi
#

MOUNT_BASE="/home/pi"
MOUNT="/usr/bin/systemd-mount"
UMOUNT="/usr/bin/systemd-umount"

# Log function
log_msg() {
    logger -t "mount-to-homepi" "$1"
}

# Check if mount tools exist
if [ ! -x "$MOUNT" ] || [ ! -x "$UMOUNT" ]; then
    log_msg "ERROR: systemd-mount or systemd-umount not found"
    exit 1
fi

# Get device name
name="$(basename "$DEVNAME")"

# Check if filesystem is supported
is_filesystem_supported() {
    while read -r fs; do
       if [ "${fs#nodev}" = "$1" ]; then
           return 0
       fi
    done < "/proc/filesystems"
    return 1
}

# Get label for mount point - only use LABEL, fallback to device name
get_label_name() {
    # Get the LABEL using blkid
    LABEL=$(/sbin/blkid -s LABEL -o value "$1" 2>/dev/null)

    # If no LABEL, try PARTLABEL
    if [ -z "$LABEL" ]; then
        LABEL=$(/sbin/blkid -s PARTLABEL -o value "$1" 2>/dev/null)
    fi

    # If still no label, use device name
    if [ -z "$LABEL" ]; then
        LABEL="$name"
    fi

    # Clean label - remove spaces and special characters
    LABEL=$(printf '%s' "$LABEL" | tr -c '[:alnum:]_-' '_')
}

# Remove directory if empty
rm_dir() {
    if test "$(find "$1" | wc -l | tr -d " ")" -lt 2 && test -d "$1"; then
        ! test -z "$1" && rm -r "$1" 2>/dev/null
    else
        log_msg "Not removing non-empty directory [$1]"
    fi
}

# Check if device is already mounted
is_mounted() {
    grep -q "^$1 " /proc/mounts
}

# Get mount point for device
get_mount_point() {
    awk -v dev="$1" '$1 == dev {print $2}' /proc/mounts
}

# Mount function
automount_homepi() {
    # Skip already mounted partitions
    if is_mounted "$DEVNAME"; then
        log_msg "$DEVNAME already mounted at $(get_mount_point "$DEVNAME")"
        return
    fi

    # Get label-based name
    get_label_name "$DEVNAME"

    # Set mount directory name
    mnt_name="$LABEL"
    mnt_dir="$MOUNT_BASE/$mnt_name"

    # Check if already cached (mounted by this script)
    if [ -e "/tmp/.automount-homepi-$mnt_name" ]; then
        log_msg "[$mnt_dir] is already cached"
        return
    fi

    # Skip partitions already in /etc/fstab
    grep -q "^[[:space:]]*$DEVNAME" /etc/fstab && return
    for n in LABEL PARTLABEL UUID PARTUUID; do
        tmp="$(lsblk -o $n "$DEVNAME" 2>/dev/null | sed -e '1d')"
        test -z "$tmp" && continue
        tmp="$n=$tmp"
        grep -q "^[[:space:]]*$tmp" /etc/fstab && return
    done

    # Check filesystem support
    if ! is_filesystem_supported "$ID_FS_TYPE"; then
        log_msg "Filesystem '$ID_FS_TYPE' on '${DEVNAME}' is unsupported"
        return
    fi

    # Skip swap and lvm
    case $ID_FS_TYPE in
        swap|lvm*|LVM*)
            return ;;
    esac

    # Create mount point if not exists
    if [ ! -d "$mnt_dir" ]; then
        mkdir -p "$mnt_dir"
        log_msg "Created mount directory: $mnt_dir"
    else
        log_msg "Mount directory already exists: $mnt_dir"
    fi

    MOUNT_OPTS="-o silent"

    # Special options for vfat/fat/exfat filesystems
    case $ID_FS_TYPE in
        vfat|fat|exfat)
            MOUNT_OPTS="$MOUNT_OPTS -o umask=007,gid=$(awk -F':' '/^disk/{print $3}' /etc/group)"
            ;;
    esac

    # Try to mount
    if ! $MOUNT $MOUNT_OPTS --no-block -t auto "$DEVNAME" "$mnt_dir"; then
        log_msg "Failed to mount $DEVNAME to $mnt_dir"
        # Only remove if directory is empty and was created by us
        if [ -z "$(ls -A "$mnt_dir" 2>/dev/null)" ]; then
            rm_dir "$mnt_dir"
        fi
    else
        log_msg "Successfully mounted $DEVNAME to [$mnt_dir]"
        echo "$mnt_name" > "/tmp/.automount-homepi-$mnt_name"
        # Change ownership to pi user if exists
        if id "pi" >/dev/null 2>&1; then
            chown pi:pi "$mnt_dir" 2>/dev/null
            log_msg "Changed ownership of $mnt_dir to pi:pi"
        fi
    fi
}

# Unmount function
autounmount_homepi() {
    # Find cache file for this device
    tmpfile=$(find /tmp -name ".automount-homepi-*" -exec grep -l "$name" {} \; 2>/dev/null | head -1)

    if [ ! -e "/sys/$DEVPATH" ]; then
        log_msg "Cleaning up $DEVNAME, unmounting from /home/pi"

        # Unmount all mount points for this device
        for mnt in $(awk -v dev="$DEVNAME" '$1 == dev {print $2}' /proc/mounts); do
            # Only unmount if it's under /home/pi
            case "$mnt" in
                /home/pi/*)
                    $UMOUNT "$mnt" 2>/dev/null
                    log_msg "Unmounted $mnt"
                    ;;
            esac
        done

        # Remove mount directory and cache file
        if [ -n "$tmpfile" ] && [ -e "$tmpfile" ]; then
            mntdir=$(cat "$tmpfile")
            rm_dir "$MOUNT_BASE/$mntdir"
            rm -f "$tmpfile"
        fi
    fi
}

# Main logic
if [ "$ACTION" = "add" ] && [ -n "$DEVNAME" ] && [ -n "$ID_FS_TYPE" ]; then
    # Check if this is not the root filesystem
    if expr "$MAJOR" \* 256 + "$MINOR" != $(stat -c %d /) >/dev/null 2>&1; then
        log_msg "Detected new device: $DEVNAME (type: $ID_FS_TYPE)"
        automount_homepi
    fi
fi

if [ "$ACTION" = "remove" ] && [ -n "$DEVNAME" ]; then
    autounmount_homepi
fi

exit 0
