#!/bin/bash

HUB_ID="5-1"
DOCK_ID="2"

# find all block devices
DEVICES=`ls -1 /sys/block/ | grep -P 's.+'`
MOUNTED_PARTITIONS=`mount | awk '{print($1);}'`

# Exit if already undocked or in progress
if [ `cat /sys/devices/platform/dock.$DOCK_ID/docked` == "0" ] \
	|| [ -e /tmp/ultrabase_eject.lock ]
then
	exit 1
fi

touch /tmp/ultrabase_eject.lock

# Syncing disks for safety
sync

for DRIVE in $DEVICES
do
	if [ $DRIVE != 'sda' ] &&
		([[ `ls -l /sys/block/$DRIVE | grep -P "usb\d/$HUB_ID/"`  ]] ||
		[ $DRIVE == 'sr0' ])
	then
		for PARTITION in  $MOUNTED_PARTITIONS
		do
			# Check if it's mounted
			if `echo $PARTITION | grep -q $DRIVE`
			then
				umount $PARTITION
				if [ $? != 0 ]
				then 
					# Do not undock when umount is failed
					echo 9 > /proc/acpi/ibm/beep
					rm /tmp/ultrabase_eject.lock
					exit 1
				fi
			fi
		done
	fi
done

# Stop Ethernet connection
/etc/init.d/net.eth0 stop

# Turn off power to the UltraBase
echo 1 >/sys/devices/platform/dock.$DOCK_ID/undock

# Misc launch
#/etc/init.d/net.wlan0 start

# Tell the user we're OK
echo 6 > /proc/acpi/ibm/beep

rm /tmp/ultrabase_eject.lock