#!/bin/dash
# jamesbond 2016, 2019
# 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_SESSION_PID=/tmp/xinitrc-session.pid.$USER.$XSESSION_ID # defined by xinitrc
CHECK_DELAY=5 # in seconds

### main
# 1. get current wm pid
read sespid < $F_SESSION_PID
[ -z "$sespid" ] && exit 1 # can't read session pid, 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 $sespid; do
	# 4. check if the program dies, then start again
	if ! kill -0 $progpid; then
		$BIN "$@" &
		progpid=$!
	fi
	sleep $CHECK_DELAY
done
