#!/bin/dash
# jamesbond 2016
# License: MIT
#
# A wrapper script for X programs that like to crash and burn
# We restart them as needed as long the current X session is still running
# Name the actual "binary" as "binary.bin", then symlink this as "binary"
#
# $@ - parameter for the actual binary

# config - from /etc/X11/xinitrc
BIN_FOLDER=/usr/crash-burn
F_WINDOW_MANAGER_PID=/tmp/xinitrc-wm.pid.$USER.$XSESSION_ID
CHECK_DELAY=5 # in seconds

### main
# 1. get current wm pid
read wmpid < $F_WINDOW_MANAGER_PID
[ -z "$wmpid" ] && exit 1 # can't read wmpid, leave

# 2. find the real binary and run it, 3 ways to do so
BIN=
# 2.a - find in special folder
[ -x $BIN_FOLDER/${0##*/} ] && BIN=$BIN_FOLDER/${0##*/}
# 2.b - find if it is renamed to .bin
[ -z "$BIN" ] && type ${0##*/}.bin > /dev/null && BIN=${0##*/}.bin
# 2.c - find if it is passed on as 1st parameter
[ -z "$BIN" ] && [ $# -gt 0 ] && type $1 > /dev/null && BIN=$1 && shift
# still no binary, leave and print message
[ -z "$BIN" ] && echo "Usage: ${0##*/} program [program parameters]" && exit 1
# now run it
$BIN "$@" &
progpid=$!

# 3. while the same wm is still alive 
while kill -0 $wmpid; do
	# 4. check if the program dies, then start again
	if ! kill -0 $progpid; then
		$BIN "$@" &
		progpid=$!
	fi
	sleep $CHECK_DELAY
done
