#!/bin/sh
# Expects a parameter either "ide" or "cf"

program=`basename $0`
media=$1

# restart syslog, if necessary
restartSyslog() {
	if [ ! -f /var/run/syslogd.pid ]; then
		echo "Restarting syslog..."
		/etc/init.d/syslog start
	fi
}

case ${media} in
	ide)
	echo "Formatting IDE disk..."
	media_dev=/dev/hda
	media_mnt=/mnt/ide
	;;

	cf)
	echo "Formatting CompactFlash..."
	media_dev=/dev/hdc
	media_mnt=/mnt/cf
	;;

	*)
	echo "usage: ${program} ide|cf";
	exit 1
	;;
esac

source /etc/init.d/mount

# unmount media if it is currently mounted
mount | grep -q ${media}
if [ $? -eq 0 ]; then

	echo "Unmounting media..."
	# Use the unmount function in /etc/init.d/mount
	unmount $media_mnt
	if [ $? -ne 0 ]; then
		# since unmount failed restart syslog
		restartSyslog

		echo "error: media in use"
		exit 1
	fi

fi

# Erase FAT16 boot record
/usr/local/bin/fatfix -f ${media_dev}

# since can't trust media state don't restart syslog if error happens now

echo "Creating new partition..."
fdisk ${media_dev} < /usr/local/bin/fdisk-input
if [ $? -ne 0 ]; then
	echo "error: media does not exist"
	exit 1
fi

media_part_dev=${media_dev}1

echo "Formatting new partition..."
mkfs -t ext3 ${media_part_dev}
if [ $? -ne 0 ]; then
	echo "error: making EXT3 file system"
	exit 1
fi

mount -t ext3 ${media_part_dev} ${media_mnt}
if [ $? -ne 0 ]; then
	echo "error: mounting EXT3 file system"
	exit 1
fi

# this should really be done by Apollo and syslog
echo "Creating directories for Apollo..."
mkdir ${media_mnt}/store
mkdir ${media_mnt}/logs

# since media successfully formatted restart syslog
restartSyslog

echo "${program} successful"
