#!/bin/bash
# Recreate fstab entries in /etc/fstab and make /mnt directories
# This script is called by udev rules, see /etc/udev/
#
# Author: Tomas M <http://slax.linux-live.org/>

PATH=$PATH:/usr/bin:/usr/sbin:/bin:/sbin
FSTAB=/etc/fstab
DEV="$1"

echo $0 $ACTION $DEV >>/var/log/udev-fstab-log

# exit if nohotplug parameter is given or shutdown is in progress
if [ "$(cat /proc/cmdline | egrep "nohd|nohotplug")" != "" -o \
     "$(runlevel | cut -d " " -f 2 | tr 0 6)" = 6 ]; then
   exit 0;
fi

. /usr/lib/liblinuxlive

if [ "$ACTION" = "add" -a -b "$DEV" ]; then
   if ! dev_is_in_fstab $FSTAB $DEV; then
      FS="`device_filesystem $DEV`"
      OPT="`fs_options $FS fstab`"
      MNT="`device_mountdir $DEV`"

      # If udev detected floppy, add it here. Thanks Quax :)
      if [ "$(echo "$DEV" | grep /fd)" != "" ]; then
         mkdir -p /mnt/floppy
         fstab_add_line $FSTAB $DEV /mnt/floppy auto rw,noauto,user,sync
      fi

      # if the partition has filesystem, add it to fstab
      # this doesn't handle HotAdded CDROMs with no media
      if [ "$FS" != "" ]; then
         fstab_add_line $FSTAB $DEV $MNT $FS $OPT
         if [ "$FS" != "swap" ]; then mkdir -p "$MNT"; fi
      fi
   fi
fi

if [ "$ACTION" = "remove" ]; then
   sed -i -r "\\;^$DEV[[:space:]].*;d" $FSTAB
fi

if [ "$ACTION" = "" -a "$DEV" = "" ]; then
   rmdir /mnt/* 2>/dev/null
   fstab_update /
fi
