#!/bin/sh

MNTLOCK=/tmp/mntlock
DEV=${DEVNAME##*/}
KERN=${DEVPATH##*/}
[ -n "`ls -d /sys$DEVPATH/$KERN* 2>/dev/null`" ] && exit 0

PART_NUM=${DEVNAME##*part}
[ "$PART_NUM" != "$DEVNAME" ] && PART=" part $PART_NUM"

if [ -n "$PART" ]; then
  DEVPATH=${DEVPATH%/*}
  [ -z "`ls -d /sys$DEVPATH/${KERN%[1-9]}* | grep -v $KERN\$`" ] && PART=
fi

VENDOR=`cat /sys$DEVPATH/device/vendor 2>/dev/null`
MODEL=`cat /sys$DEVPATH/device/model 2>/dev/null`
MNT=`echo $VENDOR$MODEL | sed s/\ *$// | sed 's|/|\\\\|g'`$PART

if [ "`cat /sys$DEVPATH/removable`" = 1 \
     -o -n "`echo $PHYSDEVPATH | grep -e usb -e ieee1394`" ]; then
  REMOVABLE=true
fi

if [ "$REMOVABLE" != true -o "$MNT" = "$PART" ]; then
  case $DEV in
    cdrom*)
      MNT="cdrom ${DEV#cdrom}"
      ;;
    disk*)
      DEV=${DEV%part*}
      MNT="disk ${DEV#disk}$PART"
      ;;
  esac
fi

flock -e $MNTLOCK
MNT="/mnt/$MNT"
if [ -d "$MNT" ]; then
  REMOUNT="remount,"
else
  REMOUNT=
  mkdir "$MNT"
fi
flock -u

case $DEV in
  cdrom*)
    mount -t iso9660,udf -o ${REMOUNT}ro $DEVNAME "$MNT" && OK=1
    if [ "$OK" != 1 ]; then
        sleep 7
        mount -t iso9660,udf -o ${REMOUNT}ro $DEVNAME "$MNT"
        OK=1
    fi
    ;;
  disk*)
    hdparm -S24 $DEVNAME >/dev/null
    if ! grep -q installator /proc/cmdline; then
      mount -o ${REMOUNT}ro $DEVNAME "$MNT" && OK=1
    fi
    if [ -n "`pidof mplayer`" ]; then
      [ -e /var/autoplay ] && mp_loader "$MNT" l
    fi
    ;;
esac

flock -e $MNTLOCK
[ "$OK" = 1 ] && echo "$DEVNAME	$MNT" >> /etc/mnts || rmdir "$MNT"
flock -u
