#!/bin/bash

## called by a INCRON rule like :
## /path/of/this/script.sh DIRECTORY DEVICE_NAME IN_CREATE,IN_ISDIR

## DIRECTORY is a directory created at startup (at least before incron startup) monitored by a incron rule like :
## DIRECTORY IN_CREATE /path/of/this/script.sh $@ $# $%

## DEVICE_NAME is a directory created by a udev rule (usable whatever the way to mount was [uuid,label,path])
## its creation will make incron call this script
## this script will analyse the name of the DEVICE_NAME to execute what_we_want

## For example, the following udev rule :
## ACTION=="add", SUBSYSTEM=="block", ENV{ID_FS_LABEL}=="gris2", RUN+="/bin/mount -L gris2", RUN+="/bin/mkdir -p /tmp/.incron.yug/%k"
## will make this script set the $rootdir, $thedevice, $theevent variables set to :
# rootdir=/tmp/.incron.yug
# newdir=sdc1 (for example)
# theevent=IN_CREATE,IN_ISDIR
## it becomes possible to spawn automatically (for example) a terminal in the following mount point as soon as the device is plugged (and mounted)
# the mount point is found by a simple mount|sed

LOGFILE=/tmp/myudev.log
rootdir=$1 && shift
thedevice=$1 && shift
theevent=$1 && shift
unset destdir

if [[ $theevent =~ IN_CREATE ]]; then
	# device as just been mounted
	destdir=$(mount|sed -n "s;^/dev/$thedevice on \(.*\) type.*$;\1;p")
	if [ -d "$destdir" ]; then
		echo "[INCRON] CREATE '$thedevice' will make urxvtc -cd $destdir" >> $LOGFILE;
		urxvtc -cd $destdir
	else
		echo "[INCRON] CREATE '$thedevice' : $destdir doesn't exist" >> $LOGFILE
	fi
elif [[ $theevent =~ IN_DELETE ]]; then
	# device as just been unmounted... useless
	echo "[INCRON] DELETE : $thedevice is gone" >> $LOGFILE
	echo $thedevice|osd_cat -o 35 -p bottom -A center -d 10 -f "-misc-dejavu serif-bold-r-normal--24-0-0-0-p-0-iso8859-15" &
	echo " UNPLUGGED"|osd_cat -i 60 -p bottom -A center -d 10 -f "-misc-dejavu serif-bold-r-normal--24-0-0-0-p-0-iso8859-15" -c blue &
else
	echo "[INCRON] OTHER EVENT ; $theevent" >> $LOGFILE
fi
#TODO : umount the FS when urxvt dies to avoid having to launch a new one to explicitely unmount
#TODO : add a temporary incron watch on the mount point to detect if it was umounted (useless)
