#!/bin/ash

#Uncomment for debug mode (don't suppress STDOUT and STDERR)
#DEBUG=1

if [ "$DEBUG" ] ; then
	qt () { "$@" ; }
else
	qt () { "$@" >/dev/null 2>&1 ; }
fi

errexit () {
	echo $1
	qt rm $IMAGE
	exit 1
}

LRPKG="/var/lib/lrpkg"
MNT="$LRPKG/mnt"
DEV="/dev/boot"
IMAGE="/tmp/LRPimage"

set -- `ls -l $DEV | \
sed 's/.*-> \/dev\/\([a-z]*\)\([0-9]*\)[a-z]*\(.*$\)/\1 \2 \3/'`

devmaj=$1
devmin=$2
size=${3:-1440}
if [ -z "$3" ] ; then
	suffix=u1440
else
	suffix=""
fi

set -- `ls -l $DEV | \
sed 's/.*-> \(\/dev\/.*$\)/\1/'`
DEVFORMAT=$1$suffix

if [ "$devmaj" != "fd" ] ; then
	echo "It doesn't look like you are booting from a Floppy Disk!"
	exit 1
fi

set -- `df | grep ram0`
avail=$4

# Check for enough free ramdisk space, with a bit leftover
if [ $avail -le $(($size + 10)) ] ; then
	echo "You don't have enough free ramdisk space to backup right now!"
	echo "Try deleting some files, or clearing some logs"
	exit 1
fi

echo "Insert your LRP boot disk"
read -p "Press enter to continue" line
echo ""

# Mount the floppy to verify it is the proper format
if qt mount -r -t `cat $LRPKG/boot.fstype` $DEV $MNT ; then
	qt umount $MNT
	echo "Reading disk:"
	dd < $DEV > $IMAGE ; status=$?
	echo ""
	if [ $status -ne 0 ] ; then
		errexit "Could not read your LRP disk!"
	fi
else
	errexit "Could not mount backup device!"
fi

set -- `df | grep ram0`
avail=$4

if [ $avail -eq 0 ] ; then
	errexit "Ran out of ramdisk space!"
fi

echo "Insert your backup disk"
echo "WARNING! Any existing data on the disk will be destroyed!"
read -p "Press enter to continue" line
echo ""

fdformat $DEVFORMAT ; status=$?

if [ $status -ne 0 ] ; then
	errexit "Could not format your backup disk!"
fi

echo "Writing disk..."

dd < $IMAGE > $DEV ; status=$?
echo ""

if [ $status -ne 0 ] ; then
	errexit "Could not write your backup disk!"
fi

qt rm $IMAGE

echo "Finished!"
echo "Keep your backup disk in a safe place, and remember to put your LRP disk"
echo "back in the drive"
