#!/bin/sh

BORKEDLABEL=`LANG=en_US /sbin/swapon -a 2>&1 | sed 's/.*cannot find the device for LABEL=//'`

if [ -n "$BORKEDLABEL" ]; then
	/usr/bin/logger -p local6.notice -t system  "checking broken swap partition label $BORKEDLABEL in /etc/fstab"

	PARTITION=`echo $BORKEDLABEL | sed 's/SWAP-/\/dev\//'`
	DISK=`echo $PARTITION | sed 's/[0-9]*$//g'`
	ISSWAP=`LANG=en_US fdisk -l "$DISK" 2>/dev/null | grep "Linux swap"`

	if [ -n "$ISSWAP" ]; then
		/usr/bin/logger -p local6.notice -t system  "making swap on $PARTITION"
		/sbin/mke2fs -q $PARTITION
		/sbin/mkswap -L $BORKEDLABEL $PARTITION
	else
		/usr/bin/logger -p local6.notice -t system  "label $BORKEDLABEL does not match disk $PARTITION - autofix unavailable"
	fi
else
	/usr/bin/logger -p local6.notice -t system  "swap partition labels ok"
fi

CHECK=`grep "/usr/share/system/scripts/swapfix" /etc/rc.d/rc.local`
if [ -n "$CHECK" ]; then
	/usr/bin/logger -p local6.notice -t system  "removing swap fix from boot"
	grep -v "/usr/share/system/scripts/swapfix" /etc/rc.d/rc.local > /etc/rc.d/rc.local.new
	mv /etc/rc.d/rc.local.new /etc/rc.d/rc.local
	chmod 755 /etc/rc.d/rc.local
fi
