#!/bin/sh
# Copyright (C) 2006 OpenWrt.org
#
# Modified by Sigma Designs - 2008
#
MOUNT_POINT=""
BDP_FIFO=/tmp/bdp.fifo
DEVPROP_FILE=prop.dev

# device size (1)
# df -k | grep i-stor | awk '{print $2}'
# device size (2)
# fdisk -l /dev/sda | grep "Disk /dev/sda" | awk '{print $3}'
# device size in bytes (3)
# SIZE= 512 * NUMBLK512=`cat /sys${DEVPATH}/${blk}/${BLK}/size`
# device's read speed
# hdparm -t /dev/sda1 | grep seconds | awk '{ print $11 }'

#
# Find out the device properties like size and transfer speed
# and write them into a file on the device
#
function device_prop()
{
	# remove any existing file
	[ -f ${MOUNT_POINT}/${DEVPROP_FILE} ] && rm -f ${MOUNT_POINT}/${DEVPROP_FILE}
	
	SIZE=`cat /sys${DEVPATH}/${blk}/${BLK}/size`
	SIZE=$(($SIZE*512))

	SPEED=`/sbin/hdparm -t /dev/${node} | grep seconds | awk '{ print $11 }'`
	SPEED=$(echo | awk -v _SPEED=${SPEED} '{ print 1000000*_SPEED }')

	touch ${MOUNT_POINT}/${DEVPROP_FILE}
	echo "SIGM" > ${MOUNT_POINT}/${DEVPROP_FILE}
	echo "SIZE=${SIZE}" >> ${MOUNT_POINT}/${DEVPROP_FILE}
	echo "SPEED=${SPEED}" >> ${MOUNT_POINT}/${DEVPROP_FILE}
}

function do_mount()
{
	i=0
	while [ $i -le 10 ]; do
		i=$(($i+1))
		if [ -d /sys${DEVPATH} ]; then
			cd /sys${DEVPATH}
			for blk in `find host* -type d`; do
				cd /sys/${DEVPATH}/${blk}
				BLK=$(find block* -type l 2> /dev/null)
				[ -n "${BLK}" ] && {
					cd /sys${DEVPATH}/${blk}/${BLK}
# 					ls /dev/ > /tmp/d
#                         		sleep 2
					for node in `find sd* -type d | grep -v "/"`; do
						FS_LABEL=`/sbin/e2label /dev/${node} 2>/dev/null`
						FS_TYPE=`/sbin/blkid -s TYPE /dev/${node} | cut -d'"' -f 2`

						if [ "$?" == "0" -a "$FS_LABEL" == "SIGM_LOCAL_STOR" ]; then
# 							echo "Internal storage"
							MOUNT_POINT="/i-stor"
						else
# 							echo "External storage"
							MOUNT_POINT="/e-stor"
						fi
						mkdir -p $MOUNT_POINT
# 						echo "mounting /dev/${node} on ${MOUNT_POINT} as ${FS_TYPE}"
						mount -t ${FS_TYPE} -o noatime,rw /dev/${node} ${MOUNT_POINT}
						# if the external storage was mounted successfully
						# and the BDP_FIFO file is present signal the
						# player application
						if [ "$?" == "0" ]; then
							mkdir -p ${MOUNT_POINT}/bdj/ada
							mkdir -p ${MOUNT_POINT}/bdj/buda

							# get the device size and speed and save them on the device
							device_prop

							if [ -p $BDP_FIFO ]; then
								echo "ESTOR:ADDED"
								echo "ESTOR:ADDED" > $BDP_FIFO
							fi
						fi
						exit 0
					done
				}
			done
			sleep 1
		fi
	done
}

case "$1" in

	add)
		do_mount
	;;
	remove)
		if [ -p $BDP_FIFO ]; then
			echo "ESTOR:REMOVED"
			echo "ESTOR:REMOVED" > $BDP_FIFO
		fi
		# lazy unmount
		umount -l /e-stor
	;;
esac
