#!/bin/bash


#    Copyright (c) 2011 Ericsson AB.
#    All rights reserved.



reportFailure() {
	if [ $1 -ne 0 ]; then
		echo "Error: $2"
		exit $1
	fi
}

find_disk() {

	# There should not be more than one USB device connected through
	# the front panel.
	for i in sda sdb; do
		readlink /sys/block/$i | grep usb >/dev/null 2>&1
		if [ $? -eq 0 ]; then
			echo $i
		fi
	done
}

# Create single partition with ext2 on external disk
format_disk() {

echo -n "Creating new partition table. Please wait ..."
fdisk /dev/$1 >/tmp/format_media_device.log 2>&1 <<+++
o
n
p
1
1

t
83
w
+++
reportFailure $? "Failed to create partition on external media."
echo "Done"

}


# Main begins here
grep "/media/flash" /proc/mounts >/dev/null 2>&1
[ $? -eq 0 ] && reportFailure 1 "External media is mounted."

disk=`find_disk`
[ -z $disk ] && reportFailure 1 "Failed to find external media."


echo -n "Creating ext2 file-system on external media, please wait..."
mke2fs -I 128 -L ssr-external /dev/${disk}1  >/tmp/format_media_device.log 2>&1
reportFailure $? "Failed to create ext2 file-system on external media."
echo Done.
exit 0
