#!/bin/sh
#
# (C) Copyright 1993, 1994 Mike Jagdis (jaggy@purplet.demon.co.uk)
#
#
# Add swap files. Swap partitions are started as soon as the system
# comes up. Swap files can only be started once the relevent file
# systems have been mounted and must be stopped before their parent
# filesystem is unmounted.

# Load the library functions and try and find various programs.
. /etc/init.d/LIB
dd=`pathof dd`
mkswap=`pathof mkswap`
swapoff=`pathof swapoff`
swapon=`pathof swapon`

case "$1" in
	start)
		echo $use_escapes "Starting swap files:\c"
		if [ -z "$dd" ]; then
			echo "WARNING: dd not found. Swap files will not be rebuilt"
		fi
		if [ -z "$mkswap" ]; then
			echo "WARNING: mkswap not found. Swap files will not be reinitialised"
		fi
		awk '/^[ \t]*\// && !/^[ \t]*\/dev/' /etc/default/swap | while read i
		do
			if [ -z "$swapon" ]; then
				echo "ERROR: swapon not found. Unable to start swap files"
				exit 1
			fi

			set $i

			echo $use_escapes " $1\c"

			# If we have enough to recreate the swap file go
			# ahead just to be sure...
			if [ -n "$dd" -a -n "$mkswap" -a -n "$2" ]; then
				rm -f $1
				$dd if=/dev/zero of=$1 bs=1k count=$2 > /dev/null 2>&1
			fi
			if [ -n "$mkswap" -a -n "$2" ]; then
				$mkswap $3 $1 $2
			fi
			if [ -f "$1" ]; then
				chmod 600 $1 > /dev/null 2>&1
				$swapon $1
			else
				echo "WARNING: $1 not found - not used for swapping"
			fi
		done
		echo
		;;

	stop)
		if [ -z "$swapoff" ]; then
			echo "ERROR: swapoff not found. Unable to stop swap files"
			exit 1
		fi
		echo $use_escapes "Stopping swap files:\c"
		awk '/^[ \t]*\// && !/^[ \t]*\/dev/' /etc/default/swap | while read i
		do
			set $i
			echo $use_escapes " $1\c"

			$swapoff $1

			# If we have enough to recreate the swap file
			# delete it. Is this a really a good idea???
			if [ -n "$dd" -a -n "$mkswap" -a -n "$3" ]; then
				rm -f $1
			fi
		done
		echo
		;;

	*)
		echo "usage: swap start|stop"
		exit 1
		;;
esac
