#!/bin/bash
#
# Copyright (c) International Business Machines  Corp., 2005
# Author: Avantika Mathur (mathurav@us.ibm.com)
#
# This library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as published by the Free Software Foundation; either
# version 2.1 of the License, or (at your option) any later version.
#
# This library is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
# Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with this library; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
#

mflags=""
#mflags="-n" # Don't futz with mtab

flag=y
while getopts "n" arg "$@"
do
        case "$arg" in
        n)      flag=n
                shift
                ;;
        esac
done

bind_type="$1"
dir="$2"


if [ ! -d "$dir" ]
then
	if [ -e "$dir" ]; then
		echo "ERROR: a file by the name \"$dir\" exists"
		exit 1
	fi
	mkdir -p "$dir"
	echo "mkdir -p \"$dir\""
fi


if [ "$flag" = "y" ] && [ "$bind_type" != slave ]
then
	mount $mflags --bind "$dir" "$dir" || exit $?
	echo "mount $mflags --bind \"$dir\" \"$dir\""
fi

# Try to use native mount, else fallback to included smount binary
case "$bind_type" in
   share)
   	echo "mount $mflags --make-rshared \"$dir\""
	mount $mflags --make-rshared "$dir" 2> /dev/null || \
	smount "$dir" rshared || exit $?
      	;;
   priv)
   	echo "mount $mflags --make-rprivate \"$dir\""
	mount $mflags --make-rprivate "$dir" 2> /dev/null || \
	smount "$dir" rprivate || exit $?
      	;;
   slave)
   	echo "mount $mflags --make-rslave \"$dir\""
	mount $mflags --make-rslave "$dir" 2> /dev/null || \
	smount "$dir" rslave || exit $?
      	;;
   unclone)
   	echo "mount $mflags --make-runbindable \"$dir\""
	mount $mflags --make-runbindable "$dir" 2> /dev/null || \
	smount "$dir" runclone || exit $?
      	;;
   nshare)
   	echo "mount $mflags --make-shared \"$dir\""
	mount $mflags --make-shared "$dir" 2> /dev/null || \
	smount "$dir" shared || exit $?
      	;;
   npriv)
   	echo "mount $mflags --make-private \"$dir\""
	mount $mflags --make-private "$dir" 2> /dev/null || \
	smount "$dir" private || exit $?
      	;;
   nslave)
   	echo "mount $mflags --make-slave \"$dir\""
	mount $mflags --make-slave "$dir" 2> /dev/null || \
	smount "$dir" slave || exit $?
      	;;
   nunclone)
   	echo "mount $mflags --make-unbindable \"$dir\""
	mount $mflags --make-unbindable "$dir" 2> /dev/null || \
	smount "$dir" unclone || exit $?
      	;;
   *)
   	echo "$0: unrecognized bind type (1st arg): $bind_type" 1>&2
	exit 1
	;;
esac