#!/bin/sh
#
# swapd		swapd Dynamic swapping manager for Linux.
#
# chkconfig:	2345 05 95
#
# description:	swapd is a dynamic swapping manager for Linux. It provides the system
#		with as much swap space (virtual memory) as is required at a
#		particular time by dynamically creating swap files. This is more
#		convinient than using fixed swap files and/or partitions because they
#		(a) are unused most of the time and are just taking up disk space; and
#		(b) provide a limited amount of virtual memory. 	


# Source function library
. /etc/rc.d/init.d/functions

RETVAL=0

SWAPDIR=`cat /etc/swapd.conf | awk '/^swapdir +\/.*/ {print $2}'`
# Above: swapd's config parser doesn't seem more sophisticated.
if ! [ -d "$SWAPDIR" ]; then
	mkdir -m700 "$SWAPDIR"
	RETVAL=$?
	if [ "$RETVAL" != "0" ]; then
		fail
		exit $RETVAL
	fi
fi

# See how we were called.
case "$1" in
  start)
	# Check if the service is already running?
	if [ ! -f /var/lock/subsys/swapd ]; then
		# show "Starting %s service" swapd
		msg_starting swapd
		busy
		#daemon /usr/sbin/swapd - seems that swapd die with this.
		swapd > /dev/null 2>&1 # be quiet!
		RETVAL=$?
		if [ "$RETVAL" = "0" ]; then
			touch /var/lock/subsys/swapd
			ok
		else
			fail
		fi
	else
		# show "%s service is already running." swapd
		msg_already_running swapd
	fi
	;;
  stop)
	if [ -f /var/lock/subsys/swapd ]; then
	# show "Stopping %s service" swapd
		msg_stopping swapd
		killproc swapd
		RETVAL=$?
		if [ "$RETVAL" = "0" ]; then
			show "Removing swapfiles"
			busy
			# Be paranoid careful.
			SWAPFILES=`echo $SWAPDIR/linux[0-9]*.swp`
			if [ "$SWAPFILES" != "$SWAPDIR/linux[0-9]*.swp" ]
			then
				for SWAPFILE in $SWAPFILES; do
					file "$SWAPFILE" |\
						grep "Linux.* swap file" \
							> /dev/null 2>&1 
					if [ $? -eq 0 ]; then
						swapoff "$SWAPFILE" && \
							rm -f "$SWAPFILE"
					fi
				done
			fi
		fi
		rm -f /var/lock/subsys/swapd
		ok
	else
		# show "%s service is not running." swapd
		msg_not_running swapd
	fi	
	;;
  restart|force-reload)
	$0 stop
	$0 start
	RETVAL=$?
	;;
  status)
	status swapd
	RETVAL=$?
	;;
  *)
	msg_usage "$0 {start|stop|restart|force-reload|status}"
	exit 3
esac

exit $RETVAL

# This must be last line !
# vi:syntax=sh:tw=78:ts=8:sw=8
