#!/bin/sh

#
# Purpose: auto-restart emerald.bin when it crashes or is signalled.
#
# Usage:
# Signal this script TERM to end emerald.bin and this script.
# Signal USR1 (reload action) is passed to emerald.bin.
# Options: This script handles option --killall, emerald.bin all others.
#

# called in this script and by kill-compiz-sessions in compiz-session
kill_others() {
	local pid ppid
	while pid=$(pgrep -U $(id -u) emerald.bin); do
		ppid=$(ps -ho ppid $pid)
		[ "$ppid" ] && kill $ppid 2> /dev/null
		kill $pid 2> /dev/null
	done
}

case "$*" in
*--help*)
	echo "usage: $0 --killall"
	"$0.bin" --help | sed -e 's/emerald\.bin/emerald/g'
	exit 0
	;;
*--version*)
	exec "$0.bin" "$@"
	;;
*--killall*)
	kill_others
	exit 0
	;;
*--replace*)
	: 'pass --replace'
	;;
'')
	: 'pass no options'
	;;
*)
	gettext 'run emerald --help for usage options' >&2
	echo
	exit 1
	;;
esac

[ "${FLOCKER}" != "$0" ] && exec env FLOCKER="$0" flock -en "$0" "$0" "$@" || :

em_pid=$$ em_restart=1 em_count=0
trap 'em_restart=0; kill $em_pid 2> /dev/null' TERM INT
trap 'em_restart=2; kill -USR1 $em_pid' USR1
while [ $em_restart -ne 0 -a $em_count -lt 100 ]; do
	if [ $em_restart -eq 1 ]; then
		"$0.bin" "$@" < /dev/null &
		em_pid=$!
		em_count=$(($em_count + 1))
	else
		em_restart=1
	fi
	wait $em_pid
	em_pid=
done
wait $em_pid
status=$?
exit $status
