#!/bin/sh
#
# V2616A-LX design a hotswap button for umount all the partitions and stop all the disks
#
file=`basename $0`
num=$1


field="\$1"

umount_partitions() {

	num=$1

	#Check partitions
	partitions=`mount | awk -F' ' "/media\/disk${num}/{print $field}" | xargs -n 10`
	if [ ! -z "$partitions" ] ; then
		echo $file: WARNING! /media/disk${num}pn should be unmounted before disk is removed
		echo $file: Force to unmount them
		for i in $partitions; do 
			umount  $i 2> /dev/null
		done
	fi
}

#Stop the disks
stop_disk() {

	host=$1
	target=$2
	path=$3

	if [ ! -f /sys/devices/pci0000:00/0000:00:1f.2/$host/$target/$path/delete ] ; then
		echo "mxhtspd: WARNING! can't remove disk $num. It may has been removed before"
		exit 0
	else
		echo 1 > /sys/devices/pci0000:00/0000:00:1f.2/$host/$target/$path/delete ;
	fi
}

# Umount all the the partitions on SATA-A disk
if [ $num -eq 1 ] ; then
	umount_partitions $num
# Stop the SATA-B disk
	host="ata5/host4"; 
	target="target4:0:0"; 
	path="4:0:0:0"
	stop_disk $host $target $path
fi
# Umount all the the partitions on SATA-B disk

if [ $num -eq 2 ] ; then
	umount_partitions $num
# Stop the SATA-B disk
	host="ata4/host3";
	target="target3:0:0";
	path="3:0:0:0"
	stop_disk $host $target $path
fi

if [ $num -eq 3 ] || [ $num -eq 4 ] ; then
	disk_num=$(($num-2))
	echo "$file: WARNING! disk${disk_num} is busy."
	
	for i in 1 2 3;
	do
	        mxhtspd-setled $disk_num 0; sleep 1
        	mxhtspd-setled $disk_num 1; sleep 1
	done
	echo "mxhtspd: Can't remove disk $disk_num. It is busy."
else
	#Light success led
	for i in 1 2 3;
	do
		mxhtspd-setled $num 1; sleep 1
		mxhtspd-setled $num 0; sleep 1
	done
	echo mxhtspd: Remove disk $num ok
fi
