#!/bin/bash
# (C) Klaus Knopper Nov 2002
# License: GNU GENERAL PUBLIC LICENSE version 2.0
# Calls scanpartitions as root and adds entries to /etc/fstab

PATH="/bin:/sbin:/usr/bin:/usr/sbin:/usr/local/sbin"
export PATH
umask 022

[ ! -e /proc/partitions ] && { echo "$0: /proc not mounted, exiting" >&2; exit 1; }

if [ -e /var/run/rebuildfstab.pid ]; then
 ps "$(</var/run/rebuildfstab.pid)" >/dev/null 2>&1 && exit 0
 rm -f /var/run/rebuildfstab.pid
fi

echo "$$" >/var/run/rebuildfstab.pid

XSH=""
[ -n "$DISPLAY" ] && XSH="rxvt -bg black -fg green -cr red -T $0 -e"

[ "`id -u`" != "0" ] && { exec $XSH sudo $0 "$@"; }


TMP="/tmp/fstab.$$.tmp"
ADDEDBYKNOPPIX="#Aadido por Trisquel"

# Simple shell grep, searches for lines STARTING with string
stringinfile(){
while read line; do
case "$line" in $1*) return 0;; esac
done <"$2"
return 1
}

removeentries(){
# Remove comment line $1 and the following line from file $2
# sed '/^# Added by KNOPPIX/{N;d;}'
while read line; do
case "$line" in $1) read line; continue ;; esac
echo "$line"
done <"$2"
}

verbose=""
remove=""
user=""
group=""
arg="$1"
while [ -n "$arg" ]; do
 case "$arg" in
  -v*) verbose="yes" ;;
  -r*) remove="yes" ;;
  -u*) shift; user="$1" ;;
  -g*) shift; group="$1" ;;
  *) echo "Usage: $0 [-v[erbose]] [-r[emove_old]] [-u[ser] uid] [ -g[roup] gid]" ;;
 esac
 shift
 arg="$1"
done

[ -n "$verbose" ] && echo "Scanning for new harddisks/partitions..." >&2
rm -f "$TMP"

if [ -n "$remove" ]; then
 removeentries "$ADDEDBYKNOPPIX" /etc/fstab >"$TMP"
else
 cat /etc/fstab >"$TMP"
fi

root="/dev/null"

count=0
while read device mountpoint fstype relax; do
 stringinfile "$device " "$TMP" || \
 { count="$((count + 1))"
   if [ "$mountpoint" != "none" ]
   then
   [ -d "$mountpoint" ] || mkdir -p "$mountpoint" 2>/dev/null
   fi
   options="auto,noatime,nodiratime" 
   case "$fstype" in
    ntfs) options="${options},umask=0,locale=es_ES.utf8" ;;
    vfat|msdos) options="${options},umask=0" ;;
    swap) options="defaults" ;;
   esac
   case "$fstype" in
   ntfs|vfat|msdos)
   [ -n "$user" ] && options="$options,uid=$user"
   [ -n "$group" ] && options="$options,gid=$group"
   ;;
   esac
   [ $device = $root ] &&  options="$options,dev,suid" && mountpoint="/"
   echo "$ADDEDBYKNOPPIX"
   if [ $device = $root ]
   then
   echo "$device $mountpoint $fstype $options 1 1 ";
   elif  echo "ext3 ext2 cramfs minix vfat xfs reiserfs reiser4 jfs"|grep $fstype >/dev/null
   then
   echo "$device $mountpoint $fstype $options 1 2 "; 
   else
   echo "$device $mountpoint $fstype $options 0 0 "; 
   fi
   }
done >>"$TMP" <<EOT
$(scanpartitions)
EOT

[ -n "$verbose" ] && { [ "$count" -gt 0 ] && echo "Adding $count new partitions to /etc/fstab." >&2 || echo "No new partitions found." >&2; }

sed -i s/"ntfs "/"ntfs-3g "/g "$TMP"

mv -f "$TMP" /etc/fstab

rm -f /var/run/rebuildfstab.pid

exit 0
