|
#!/bin/bash
##---------------------------------------------------------------------------##
#
# Script: inotifydev-sd-device
# Author: Brian <genius@groupbcl.ca> :)
# Date: September 2017
#
# USB drive handler for inotifydev.
#
# When mounting a drive, this script attempts to assign the device and
# the mount point to a logged in user. It determines the user by listing
# all non-root processes, determining their owners, then searching the
# 'passwd' for file users that don't have 'nologin' as their login shell.
#
##---------------------------------------------------------------------------##
# BUUS: This script is part of Brian's Useful Utilities Set
##---------------------------------------------------------------------------##
function on_create {
# Search for an active user that isn't root by listing non-root processess
# and searching the process owners for a user that can log in
EGREP_LIST=''
for U in $(ps -ef | grep -v -e ^UID -e ^root | cut -f 1 -d' ' | sort -u)
do
[ "$EGREP_LIST" ] && EGREP_LIST="$EGREP_LIST|"
EGREP_LIST="${EGREP_LIST}${U}"
done
MOUNT_USER="$(egrep "^($EGREP_LIST):" /etc/passwd | grep -v nologin |
head -n 1 | cut -f1 -d:)"
MOUNT_OPTS=''
if [ "$MOUNT_USER" ]
then
MOUNT_OPTS="uid=$MOUNT_USER,gid=$MOUNT_USER"
ps -ef | grep -v grep | grep -q udisksd &&
MOUNT_OPTS="${MOUNT_OPTS},uhelper=udisks2"
fi
# Get information for the device such as PTTN, LABEL, TYPE, UUID
LINE="$(blkid /dev/$DEVICE)"
eval "$(echo "$LINE" | sed 's,\(/dev/sd[a-z][0-9]*\+\):,PTTN=\1,')"
# If the partiion has a LABEL, see if it's mounted already
if [ "$LABEL" ]
then
PTTN_RE="${PTTN//\//\\/}"
MOUNT_PT="$(mount | awk "{
if (match(\$0, /^$PTTN_RE on (.*) type [[:alnum:]]+ \\(/, a))
{ print a[1] }
}")"
[ "$MOUNT_PT" ] && echo "$PTTN is already mounted on $MOUNT_PT"
else
echo "Partition /dev/$DEVICE does not have a file system label"
fi
# If there is a LABEL and no mount point, attempt to mount the device
if [ "$LABEL" -a ! "$MOUNT_PT" ]
then
[ "$MOUNT_USER" ] && chown $MOUNT_USER $PTTN
MOUNT_PT="/tmp/${DEVICE} ${LABEL}" # Set mount point to "/tmp/sdX_LABEL"
[ -d "$MOUNT_PT" ] || mkdir "$MOUNT_PT"
echo $TYPE | egrep -q '(fat|ntfs)' && MOUNT_OPTS="$MOUNT_OPTS,dmask=022,fmask=113"
MOUNT_OPTS="$MOUNT_OPTS,defaults"
echo "Attempting to mount $PTTN on '$MOUNT_PT', type $TYPE"
echo "Mount options: $MOUNT_OPTS"
mount -t $TYPE -o $MOUNT_OPTS $PTTN "$MOUNT_PT"
#[ $? == 0 ] && ls "$MOUNT_PT" | sed "s,^,- $MOUNT_PT/,"
fi
}
function on_delete {
ls -d /tmp/${DEVICE}* &>/dev/null
[ $? == 0 ] || return
ls -d /tmp/${DEVICE}* | while read MOUNT_PT
do
echo "Removing mount point '$MOUNT_PT'"
if [ $(ls "$MOUNT_PT" | wc -l) -gt 0 ]
then
echo "(Attempting to force unmount disconnected device)"
umount -f "$MOUNT_PT"
fi
rmdir "$MOUNT_PT"
done
}
FUNCTION=$1
DEVICE=$2
case $1 in
CREATE) on_create;;
DELETE) on_delete;;
esac
# vim: tabstop=4
|