#!/bin/ash
# update drive icon based on whether it is mounted or unmounted
# (C) James Budiono 2012, 2015
# License: GNU GPL Version 3 or later
#
# Called with: $1-devname (with /dev/ prefix)
# Note: assumed that $USER and $DISPLAY points to the right user/display
#       (rox_set_icon_image will be run as $USER and $DISPLAY)
#

### configuration
. $BOOTSTATE_PATH # AUFS_ROOT
TEMPLATE_DRIVE_ICON_ROOT=/tmp/fatdog-drive-icons	# will be appended with $USER

# get the rox functions
. /usr/sbin/fatdog-drive-icon-roxlib.sh # rox_set_icon_image

############### helpers ###############
# $1-devname
get_mount_point() {
	dmdev=$(ls -l /dev/mapper/* 2> /dev/null | awk -v dmdev=${1##*-} '$6 == dmdev {print $10; exit; }')
	[ "$dmdev" ] || dmdev=$(ls -l /dev/mapper/* 2> /dev/null | awk -v dmdev=/${1##*/}$ '$NF ~ dmdev { print $(NF-2); exit; }')
	awk -v dev=$1 -v dmdev=$dmdev '$1 == dev || $1 == dmdev { print $2; exit; }' /proc/mounts
}

# $1-devname 
get_icon_dir() {
	icondir=$TEMPLATE_DRIVE_ICON_ROOT.$USER.$XSESSION_ID/${1##*/}	
	if ! [ -e $icondir ]; then	# may LVM - convert to actual dm-xxx name
		dmdev=$(ls -l /dev/mapper 2>/dev/null | awk -v dmdev=${1##*/} '$10 == dmdev {print "dm-" $6; exit;}')
		[ "$dmdev" ] || dmdev=$(ls -l /dev/mapper 2>/dev/null | awk -v dmdev=${1##*/} '$(NF-2) == dmdev {sub(/.*\//,"",$NF); print $NF; exit;}')
		icondir=$TEMPLATE_DRIVE_ICON_ROOT.$USER.$XSESSION_ID/$dmdev
	fi
}


############### main ###############
mountpoint=$(get_mount_point $1)
get_icon_dir ${1##*/} # returns icondir

iconfile=$icondir/.DirIcon
[ ! -e $iconfile ] && exit # continue	# don't do if our icon file is not there

if [ "$mountpoint" ]; then
	# mounted, add mounted status if not already added
	if ! grep -qF "<rect" $iconfile 2> /dev/null; then
		sed -i -e 's_</svg>__' $iconfile	
		case $mountpoint in
			# system - don't allow to unmount, yellow colour
			$AUFS_ROOT*) cat >> $iconfile << EOF
<rect x="2" y="2" width="12" height="12" fill="#ffff00" stroke="black" stroke-width="2"/>
</svg>			
EOF
			;;
			# normal - use green colour
			*)	cat >> $iconfile << EOF
<rect x="2" y="2" width="12" height="12" fill="#00ff00" stroke="black" stroke-width="2"/>
<line x1="2" y1="2" x2="14" y2="14" stroke="black"/>
<line x1="2" y1="14" x2="14" y2="2" stroke="black"/>
</svg>			
EOF
			;;
		esac
	fi
else
	# removed, remove mounted status if not already removed
	if grep -qF "<rect" $iconfile 2> /dev/null; then
		sed -i -e '/rect/ d; /line/ d' $iconfile
	fi		
fi
rox_set_icon_image $icondir $iconfile

