#!/bin/bash
# This script mounts the sdcard on startup, if available.
# Also called for hotplug events.
#
# There are some echo calls in here, note that you won't see them unless
# you start udevd with --debug which will result in vast amount of console output.
# udevd is started by /etc/init.d/udev
#

#
# If set to something different than 'no' a logfile will be created on /opt/extparam
# which will contain some content of available udev variables.
# This is meant to be used for debugging purposes only.
# During rcS there is no other writable partition available than /opt/extparam.
# Also logger is started in rc5 but udev is started early in rcS.
# IF USED HAVE IN MIND THAT YOU NEED TO REMOVE THE LOG MANUALLY!
#
CREATE_LOG=no
LOGFILE=/opt/extparam/sdcard.log

me="[sdcard]"

MOUNT="/bin/mount"
UMOUNT="/bin/umount"

MOUNTPOINT="/opt/card"
# For a simple security check.
EXPECTED_DEVICE_NAME="/dev/mmcblk1p1"

[ "${CREATE_LOG}" != "no" ] && touch ${LOGFILE} \
                            && echo "" >> ${LOGFILE} \
                            && echo $(date) >> ${LOGFILE} \
                            && echo "ACTION:     ${ACTION}" >> ${LOGFILE} \
                            && echo "DEVNAME:    ${DEVNAME}" >> ${LOGFILE} \
                            && echo "SUBSYSTEM:  ${SUBSYSTEM}" >> ${LOGFILE} \
                            && echo "ID_FS_TYPE: ${ID_FS_TYPE}" >> ${LOGFILE} \
                            && echo "ID_PART_ENTRY_SCHEME: ${ID_PART_ENTRY_SCHEME}" >> ${LOGFILE}

#
# Check if the passed device is blacklisted.
#
for line in `grep -v ^# /etc/udev/mount.blacklist`
do
  if [ ` expr match "$DEVNAME" "$line" ` -gt 0 ]
  then
    echo "${me} [$DEVNAME] is blacklisted, ignoring"
    exit 0
  fi
done

mount_scard()
{ # Only try to mount if the 1st partition of mmcblk1 is vfat recognized.
  if [ "${ID_FS_TYPE}" = "vfat" ]
  then
    echo "${me} Try mounting [${DEVNAME}] to [${MOUNTPOINT}] ... "
    MOUNT="$MOUNT -o umask=007,gid=`awk -F':' '/^disk/{print $3}' /etc/group`"

    ${MOUNT} -t vfat -o rw,suid,sync,noatime ${DEVNAME} ${MOUNTPOINT}
    if [ $? -eq 0 ]
    then
      echo "${me} done."
    else
      echo "${me} failed!"
    fi
	else
		echo "${me} No VFAT recognized for plugged in SD-Card!"
	fi
}

if [ "$ACTION" = "add" ] && [ -n "$DEVNAME" ] && [ -n "$ID_FS_TYPE" ]
then
  [ "${CREATE_LOG}" != "no" ] && echo "${me} Recognized add ACTION for device: ${DEVNAME} with ID_FS_TYPE: ${ID_FS_TYPE}." >> ${LOGFILE}
  
  if [ "${DEVNAME}" = "${EXPECTED_DEVICE_NAME}" ]
  then
    grep -q "^$DEVNAME " /proc/mounts || mount_scard
  fi
fi

if [ "$ACTION" = "remove" ] && [ -x "$UMOUNT" ] && [ -n "$DEVNAME" ]
then
  [ "${CREATE_LOG}" != "no" ] && echo "${me} Recognized remove ACTION for device: ${DEVNAME}." >> ${LOGFILE}
  for mnt in `cat /proc/mounts | grep "$DEVNAME" | cut -f 2 -d " " `
  do
  [ "${CREATE_LOG}" != "no" ] && echo "${me} Unmounting ${mnt}." >> ${LOGFILE}
    $UMOUNT $mnt
  done
fi

