#!/bin/dash
# (C) James Budiono, 2013, 2015
# License: GPL Version 3 or later.
#
# run as per-user X daemon (e.g from /etc/xdg/Startup)
#
### configuration
FLAG_BASE=/tmp/redraw-icons
FLAG=$FLAG_BASE.$$
FLAG2=$FLAG_BASE-kill.$$
grep -q sandbox /etc/shinit && IN_SANDBOX=1
#exec 2> /dev/null

### main
# kill process run by the same username
for p in ${FLAG_BASE}.*; do
	! [ -f $p ] && continue
	if [ $(stat -c %u $p) -eq $(id -u) ]; then
		pid=${p##*.}
		
		# check if process is still up
		if kill -0 $pid 2>/dev/null; then
			disp="$(tr '\0' '\n' < /proc/$pid/environ | sed '/DISPLAY=/!d;s/DISPLAY=//')"
			[ $disp = $DISPLAY ] && touch $FLAG_BASE-kill.$pid && rm -f $p # same display, kill it
		else
			[ $IN_SANDBOX ] || rm -f $p # process already dead, remove its ghosts
		fi
	fi
done

trap 'rm -f $FLAG $FLAG2; exit;' 0 INT TERM HUP
touch $FLAG
inotifyd - $FLAG:e | while read p; do
	! [ -e $FLAG2 ] &&
	fatdog-drive-icon-redraw-icons.sh
done
