#! /bin/sh
#
# Mount local filesystems and activate swap
#

#locate and source functions script
source `PATH=$INIT_D/:${0%/*}/:${0%/*/*}/:${0%/*/*/*}/ type -p functions`

case "$1" in
  start)
     need $checked_filesystems || exit_if_fatal_error

     echo 'Remounting root file system in read-write mode...'
     mount -n -o remount,rw /
     up_evaluate_retval || exit_if_any_error
     
     #clear mtab to make sure there is no wrong data that could confuse
     #the following mounting of /proc
     echo > $INIT_ROOT/etc/mtab
     
     #try to mount /proc to have /proc/mounts available
     mount -t proc proc /proc 2>/dev/null
     
     #try to copy /proc/mounts to /etc/mtab to get correct information
     #about filesystems
     #We filter the entry for the / partition if it is called /dev/root
     #because older versions of e2fsck are unable to deal with it properly.
     #If we filter it out, we use a fake mount to add it back with the name
     #from fstab (which said old e2fsck version expects)
     if [ -e /proc/mounts ]; then 
        x="`expr "$(</proc/mounts)" : '\(.*\)'$'/dev/root[ \t].*'`"
        y="`expr "$(</proc/mounts)" : $'.*/dev/root[ \t][^\n]*\n''\(.*\)'`"
        if [ -n "$x" ]; then x="$x"$'\n' ; fi
        if [ -n "$y" ]; then y="$y"$'\n' ; fi
        if [ -n "$x$y" ]; then  
            echo -n "$x$y" > $INIT_ROOT/etc/mtab
            mount -f /
        else
            cp /proc/mounts $INIT_ROOT/etc/mtab 2>/dev/null
        fi    
     fi  
     
     echo 'Mounting local filesystems...'
     if [ ! -r /etc/fstab ]; then
         echo -n 'Cannot read /etc/fstab => cannot mount local filesystems!'
         print_status failed
         exit 1
     else
       mount -a
       up_evaluate_retval || exit_if_any_error
     fi  
     
     #add swap space *after* mounting filesystems because swap files might
     #be located on an otherwise unmounted fs (is this really an issue?)
     echo Adding swap space...
     dmesg -n6 #prevent message from swapon
     swapon -a
     up_evaluate_retval 
     dmesg -n7 #allow all messages again  
     ;;
  stop)
     #deactivate swap *before* unmounting filesystems because swap files might
     #prevent unmounting of fs (is this really an issue?)
     echo 'Deactivating swap...'
     swapoff -a
     up_evaluate_retval
     
     #first fake the mount so that mtab is written properly as long
     #as / still mounted rw
     mount -f -o remount,ro /
     
     #unmount all filesystems except devfs and proc to avoid "none busy"
     #warning. / is remounted read-only because it can't be unmounted
     echo 'Unmounting local fs and remounting / read-only...'
     umount -a -r -t nodevfs,noproc
     up_evaluate_retval || exit_if_any_error
     ;;
  *)
     exit 1
     ;;
esac
    
exit 0
