#!/bin/bash
#
# Simple script to add icons for every halevt mount event to the roxfiler
# desktop
#
# 20110106 MV: rewrite

# Uncomment to enable logging
#exec >> /tmp/roxplug.log 2>&1
#set -x 

# Where to keep the list of icon positions
POSITION=~/.halevt/icons
# Start X position of the icon list
BASEX=10
# Start Y position of the icon list
BASEY=10
# Axis to expand the icons over
AXIS=x
# Spacing between icons
XSPACING=100
YSPACING=70

add()
{
   MOUNTPOINT="$1"

   if test "`grep \"	$MOUNTPOINT$\" $POSITION`" = ""
   then
      freepos=`grep "^..$" $POSITION | head -1`

      if test "$freepos" != ""
      then
         sed -i "s|$freepos|$freepos	$MOUNTPOINT|" $POSITION
         if test "$AXIS" = "x"
         then
            xpos=$(( $BASEX + ( ($freepos - 1) * $XSPACING ) ))
            ypos=$BASEY
         else
            xpos=$BASEX
            ypos=$(( $BASEY + ( ($freepos - 1)* $YSPACING ) ))
         fi

         rox --RPC << EOF
<?xml version="1.0"?>
<env:Envelope xmlns:env="http://www.w3.org/2001/12/soap-envelope">
 <env:Body xmlns="http://rox.sourceforge.net/SOAP/ROX-Filer">
  <PinboardAdd>
   <Path>$MOUNTPOINT</Path>
   <X>$xpos</X>
   <Y>$ypos</Y>
   <Label>$MOUNTPOINT</Label>
  </PinboardAdd>
 </env:Body>
</env:Envelope>
EOF
      fi
   fi
}

remove()
{
   MOUNTPOINT="$1"

   pos=`grep "^..	$MOUNTPOINT$" $POSITION | head -1 | cut -d'	' -f 1`

   if test "$pos" != ""
   then
      sed -i "s|$pos.*|$pos|" $POSITION
      rox --RPC << EOF
<?xml version="1.0"?>
<env:Envelope xmlns:env="http://www.w3.org/2001/12/soap-envelope">
 <env:Body xmlns="http://rox.sourceforge.net/SOAP/ROX-Filer">
  <PinboardRemove>
   <Path>$MOUNTPOINT</Path>
   <Label>$MOUNTPOINT</Label>
  </PinboardRemove>
 </env:Body>
</env:Envelope> 
EOF
   fi
}

clean()
{
   cat $POSITION | while read POS MOUNT
   do
      if test ! -d "$MOUNT" -a "$MOUNT" != ""
      then
         remove "$MOUNT"
      fi
   done
}

main()
{
   clean
   case "$1" in
   "add") 
      if test "$2" != ""
	  then
	  shift
         add "$*"
      fi
   ;;
   "remove") 
      shift
      remove "$*"
   ;;
   esac
}

main $*
