#!/bin/sh

PATH=/usr/local/sbin:/usr/local/bin:/sbin:/bin:/usr/sbin:/usr/bin
DESC="quota service"

# names of binaries
check=/sbin/quotacheck
on=/sbin/quotaon
off=/sbin/quotaoff
quotaisoff=/var/lib/quota/off
quotaisnew=/var/lib/quota/new

ALLFLAGS=-aug
USERFLAGS=-uc
GROUPFLAGS=-gc

set -e

case "$1" in
  start)
	# Check if quota already has been enabled
	quotaon -ap|grep -q "is on" && exit 0

	# Check all filesystems if quota is new or wasn't shut down correctly
	echo 'Checking quotas...';
	if [ -x $check -a \( ! -f $quotaisoff -o -f $quotaisnew \) ]; then
		$check $ALLFLAGS
		echo 'done.'
	else
		# if some filesystems are new check just these filesystems	
		fs=`awk '/usrquota/ {if ($3 == "xfs") next; print $2}' /etc/fstab`
		for i in $fs
		do
		        if test ! -e $i/quota.user -a ! -e $i/aquota.user; then
				echo "Warning: user quota not configured in filesystem \`$i.'"
			elif test ! -e $i/aquota.user; then
				test ! -s $i/quota.user && $check $USERFLAGS $i
			elif test ! -s $i/aquota.user; then
				$check $USERFLAGS $i
			fi
		done

		fs=`awk '/grpquota/ {if ($3 == "xfs") next; print $2}' /etc/fstab`
		for i in $fs
		do
		        if test ! -e $i/quota.group -a ! -e $i/aquota.group; then
				echo "Warning: group quota not configured in filesystem \`$i.'"
			elif test ! -e $i/aquota.group; then
				test ! -s $i/quota.group && $check $GROUPFLAGS $i	
			elif test ! -s $i/aquota.group; then
				$check $GROUPFLAGS $i	
			fi
		done

		echo 'done.'
	fi

	# Turn quotas on.
	if [ -x $on ]
	then
	   echo 'Turning on quotas.';
	   $on $ALLFLAGS
	fi

	# Remove quota-off and quota-new files
	rm -f $quotaisoff $quotaisnew
	;;
  stop)
	echo -n 'Turning off quotas'
	if [ -x $off ]
	then
        	$off $ALLFLAGS
		# Create quota-on file
		touch $quotaisoff
	fi
	echo "."
	;;
  restart|force-reload)
	#
	#	If the "reload" option is implemented, move the "force-reload"
	#	option to the "reload" entry above. If not, "force-reload" is
	#	just the same as "restart".
	#
	$0 stop
	$0 start
	;;
  *)
	echo "Usage: $0 {start|stop|restart|force-reload}" >&2
	exit 1
	;;
esac

exit 0
