#!/bin/bash

#VERBOSE_JER="-v"
CHROOT_PATH="/mnt/webcam-gen"
WEBCAM_GEN_WAS_MOUNTED="no"
KEEPS_WAS_MOUNTED="no"
PROC_WAS_MOUNTED="no"

function cleanup()
{
if [[ ! $KEEPS_WAS_MOUNTED == "yes" ]]
then
	if mount|grep -q 'webcam-gen/keeps'
	then
		if umount $VERBOSE_JER ${CHROOT_PATH}/keeps
		then
			echo " * Unmounted webcam-gen/keeps successfully..."
		fi
	else
	 	echo " * There was no webcam-gen/keeps to unmount"
	fi
fi

if [[ ! $KEEPS_WAS_MOUNTED == "yes" ]]
then
	if mount|grep -q 'webcam-gen/proc'
	then
		if umount $VERBOSE_JER ${CHROOT_PATH}/proc
		then
		 	echo " * Unmounted webcam-gen/proc successfully..."
		fi
	else
	 	echo " * There was no webcam-gen/proc to unmount"
	fi
fi

if [[ ! $WEBCAM_GEN_WAS_MOUNTED == "yes" ]]
then
	if mount|grep -q 'webcam-gen'
		then
			if umount $VERBOSE_JER ${CHROOT_PATH}
			then
				echo " * Unmounted webcam-gen successfully..."
			fi
		else
			echo " * There was no webcam-gen to unmount"
	fi
fi
}

function mountkeepsandproc()
{
if mount|grep -q 'webcam-gen'
then
	WEBCAM_GEN_WAS_MOUNTED="yes"
	echo " * webcam-gen was already mounted"
else
	echo -n " * Mounting webcam-gen... "
	if mount $VERBOSE_JER $CHROOT_PATH
	then
		echo "Mounted webcam-gen successfully"
	fi
fi
	
if mount|grep -q 'webcam-gen/proc'
then
	PROC_WAS_MOUNTED="yes"
	echo " * webcam-gen/proc already mounted"
else
	echo -n " * Mounting webcam-gen/proc... " 
	if mount $VERBOSE_JER -t proc none ${CHROOT_PATH}/proc
	then
		echo "Mounted webcam-gen/proc successfully"
	fi
fi

if mount|grep -q 'webcam-gen/keeps'
then
	KEEPS_WAS_MOUNTED="yes"
	echo " * webcam-gen/keeps already mounted"
else
	echo -n " * Mounting webcam-gen/keeps... "
	if mount $VERBOSE_JER --bind /keeps/ ${CHROOT_PATH}/keeps
	then
		echo "Mounted webcam-gen/keeps successfully"
	fi
fi
}

if [[ $* == "-c" ]]
then
	echo " * Cleaning up..."
	cleanup
else
	mountkeepsandproc
	chroot $CHROOT_PATH /bin/bash
	cleanup
fi

