#!/bin/sh

set -e

# Mount a filesystem
# $1: mount options
# $2: mount device
# $3: mount location
do_mount()
{
    if [ "$AUTH_VERBOSITY" = "verbose" ]; then
	echo "Mounting $2 on $3"
    fi
    mount $VERBOSE $1 "$2" "$3"
}

# Unmount a filesystem
# $1: mount location
do_umount()
{
    if [ "$AUTH_VERBOSITY" = "verbose" ]; then
	echo "Unmounting $1"
    fi
    if [ -d "$1" ]; then
	umount "$1" || true
    fi
}

# Unmount all filesystem under specified location
# $1: mount base location
do_umount_all()
{
    for dir in $(mount | grep $1 | sed -e 's/.* on \(.*\) type.*/\1/' | sort -r); do
	do_umount "$dir"
    done
}

if [ "$AUTH_VERBOSITY" = "verbose" ]; then
  VERBOSE="-v"
#  FSCK_VERBOSE="-V"
fi

if [ "$CHROOT_TYPE" = "plain" ] || [ "$CHROOT_TYPE" = "file" ] || [ "$CHROOT_TYPE" = "block-device" ] || [ "$CHROOT_TYPE" = "lvm-snapshot" ]; then

    if [ "$CHROOT_TYPE" = "plain" ]; then
	CHROOT_MOUNT_OPTIONS="--bind"
	CHROOT_MOUNT_DEVICE="$CHROOT_LOCATION"
    fi

    if [ "$CHROOT_TYPE" = "lvm-snapshot" ]; then
	CHROOT_MOUNT_DEVICE="$CHROOT_LVM_SNAPSHOT_DEVICE"
    fi

    if [ $1 = "setup-start" ] || [ $1 = "setup-recover" ]; then

        # fsck doesn't like being run non-interactively
	#/sbin/fsck $FSCK_VERBOSE -n "$CHROOT_MOUNT_DEVICE"

        if [ ! -d "$CHROOT_MOUNT_LOCATION" ]; then
	    mkdir -p "$CHROOT_MOUNT_LOCATION"
        fi
	if [ ! -d "$CHROOT_MOUNT_LOCATION" ]; then
	    echo "$CHROOT_MOUNT_LOCATION does not exist, and could not be created"
	    exit 1
	fi

        # If recovering, we want to remount all filesystems to ensure
        # a sane state.
	if [ $1 = "setup-recover" ]; then
	    do_umount_all "$CHROOT_MOUNT_LOCATION"
	fi

	if [ "$CHROOT_TYPE" != "file" ]; then
	    do_mount "$CHROOT_MOUNT_OPTIONS" "$CHROOT_MOUNT_DEVICE" "$CHROOT_MOUNT_LOCATION"
	fi

	do_mount "-t proc"    "proc"     "${CHROOT_PATH}/proc"
	do_mount "-o rw,bind" "/dev/pts" "${CHROOT_PATH}/dev/pts"
	do_mount "-t tmpfs"   "tmpfs"    "${CHROOT_PATH}/dev/shm"
	do_mount "-o rw,bind" "/home"    "${CHROOT_PATH}/home"
	do_mount "-o rw,bind" "/tmp"     "${CHROOT_PATH}/tmp"

    elif [ $1 = "setup-stop" ]; then

	do_umount "${CHROOT_PATH}/tmp"
	do_umount "${CHROOT_PATH}/home"
	do_umount "${CHROOT_PATH}/dev/shm"
	do_umount "${CHROOT_PATH}/dev/pts"
	do_umount "${CHROOT_PATH}/proc"

	if [ "$CHROOT_TYPE" != "file" ]; then
	    do_umount "$CHROOT_MOUNT_LOCATION"

	    if echo "$CHROOT_MOUNT_LOCATION" | grep -q "^$MOUNT_DIR/"; then
		rmdir "$CHROOT_MOUNT_LOCATION" || true
	    fi
	fi

    fi

fi

