#! /bin/bash

# $Id$
# Copyright (c) 2002-2007 by Thomas Lange

# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
fstab_mount() {

    if [ $fstabcount -eq 1 ]; then
        # mount the root partition; then mount the rest according to fstab found
	umount_local_disks
	mount -o ro /dev/$fstabpart $FAI_ROOT
	mount2dir $FAI_ROOT $FAI_ROOT/etc/fstab 0 ro
	df
    fi
    [ $fstabcount -eq 0 ] && echo "No /etc/fstab found"
    [ $fstabcount -ge 2 ] && echo -n "Found multiple /etc/fstab files in : $fstablist.\nUse mount2dir for mounting."
}
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
mount_local_disks() {

    # try to mount all local disk partitions
    local mountoption=ro
    local disk partition partitions
    fstabcount=0
    [ "$1" = "rw" ] && mountoption=$1

    for disk in $disklist; do
	partitions=`LC_ALL=C file -s /dev/${disk/%disc/part}?* | \
	    egrep -v " empty$|  data$| extended partition table" | \
	    perl -ne 'print "$1\n" if m#^/dev/(\S+):\s#'`
	for partition in $partitions; do
	    mkdir -p $FAI_ROOT/$partition
	    mount -o $mountoption /dev/$partition $FAI_ROOT/$partition
	    # \ && echo $partition mounted successfully
	    if [ -f $FAI_ROOT/$partition/etc/fstab ]; then
		echo "/etc/fstab found in $partition"
		fstabpart=$partition   # used in fstab_mount
		fstablist="$fstablist $partition"
		(( fstabcount += 1 ))
	    fi
	done
    done
    mount | grep $FAI_ROOT
}
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -
umount_local_disks() {

    # can be an extern script
    local part
    test -d $FAI_ROOT || return
    for part in `grep $FAI_ROOT /proc/mounts | cut -d ' ' -f 2| sort -r`; do
	umount $part
    done
    test -d $FAI_ROOT/ida && rmdir $FAI_ROOT/ida/*
    test -d $FAI_ROOT/rd && rmdir $FAI_ROOT/rd/*
    rmdir $FAI_ROOT/*
    umount $FAI_ROOT
}
# - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - - -

# main program

while getopts uf opt ; do
      case "$opt" in
        u) umount_local_disks ; exit ;;
        f) mount_local_disks; fstab_mount ; exit ;;
      esac
done
mount_local_disks
