#! /bin/sh
#
# Copyright (c) 2001-2005 SuSE Linux AG, Nuernberg, Germany.
# All rights reserved.
#
# /etc/init.d/boot.swap
#
### BEGIN INIT INFO
# Provides:          boot.swap
# Required-Start:    boot.localfs
# Should-Start: boot.lvm boot.crypto boot.lkcd
# Required-Stop:
# Default-Start:     B
# Default-Stop:
# Description:       start rest of swap devices
### END INIT INFO

. /etc/rc.status
. /etc/sysconfig/kernel

get_swap_id() {
    local line;
    type -p fdisk >/dev/null || return
    fdisk -l | while read line; do
	case "$line" in
	/*Linux\ [sS]wap*) echo "${line%% *}"
	esac
    done
}

check_swap_sig () {
    local part="$(get_swap_id)"
    local where what type rest p c
    while read  where what type rest ; do
	test "$type" = "swap" || continue
	c=continue
	for p in $part ; do
	    test "$p" = "$where" && c=true
	done
	$c
	case "$(dd if=$where bs=1 count=6 skip=4086 2>/dev/null)" in
	S1SUSP|S2SUSP) mkswap $where
	esac
    done < /etc/fstab
}

rc_reset

case "$1" in
    start)
	#
	# After mounting we may activate swap files in /etc/fstab
	# .. this should work know with the new swapon behavio(u)r
	#
	# Check for swap signature only if sysfs is not mounted
	# (then we have no way of knowing if swsuspend is enabled)
	# or if /sys/power exists (then we are sure it is enabled).
	if [ ! -d "/sys/devices" ] || [ -d "/sys/power" ]; then
	    check_swap_sig
	fi
	echo "Activating remaining swap-devices in /etc/fstab..."
	swapon -a &> /dev/null
	rc_status -v1 -r
	;;
    stop)
	echo "Turning off swap"
	sync ; sync
	rc_reset
	swapoff -a &> /dev/null
	rc_status -v1 -r
	# Something forgotten?
	if test -r /proc/swaps ; then
	    # Use cat and a pipe because swapoff changes
	    # /proc/swaps during direct read call
	    cat /proc/swaps | \
	    while read des rest ; do
		test "$des" = "Filename" && continue
		swapoff $des &> /dev/null
	    done
	fi
	;;
    restart)
	$0 stop
	$0 start
	;;
    status)
	rc_failed 4
	rc_status -v
	;;
    *)
	echo "Usage: $0 {start|stop|status|restart}"
	exit 1
	;;
esac

rc_exit

