#!/bin/sh -ex

# Need root
[ "$(id -u)" -eq 0 ] || /usr/local/bin/sudo "${0}" "${@}"

# Return true if the specified filesystem is mounted with the given type; false otherwise
# Does not handle swap entries in fstab
is_mounted() {
  src="${1}"
  dir="${2}"
  type="${3}"
  mount | while read msrc on mdir mtype mflags
  do
    mtype="${mtype##(}"
    mtype="${mtype%%,}"
    mtype="${mtype%%)}"
    [ "${dir}" = "${mdir}" -a "${type}" = "${mtype}" ] && break
  done
  return $?
}

# Return all the useful lines from the fstab file
fstab() {
  sed -e 's/#.*$//; /^[[:space:]]*$/d' "$(dirname "${0}")/fstab"
}

# Perform mount for all unmounted filesystems in fstab
do_mount() {
  fstab | while read src dir type flags fsck dump extra
  do
    if ! is_mounted "${src}" "${dir}" "${type}"
    then
      mkdir -p "${dir}"
      mount -t "${type}" -o "${flags}" "${src}" "${dir}"
    fi
  done
  true
}

# Perform umount for all mounted filesystems in fstab
do_umount() {
  fstab | tail -r | while read src dir type flags fsck dump extra
  do
    if is_mounted "${src}" "${dir}" "${type}"
    then
      umount "${dir}"
    fi
  done
  true
}

case "$(basename "${0}")" in
mount)   do_mount  ;;
umount)  do_umount ;;
esac