#!/bin/bash
# This script was written by Daniele Favara <danjele@gmail.com>
# 
CMD=ivman
CONFDIR=  # the config dir | null
EXITWITH=
SESSION=
set -x
while [ ! -z "$1" ];do
    case "$1" in
      --help|-h)
	    echo "Usage: ivman-launch [OPTIONS]"
		echo "Please see 'man ivman-launch' for details."
        exit 
        ;;
      --confdir|-c)
        if [ "x$2" != "x" ];then
            CONFDIR=$2
            if [ -d "$CONFDIR" ]; then
                CMD="$CMD --confdir $CONFDIR"
                shift 2
            else
                echo "Error $CONFDIR: No such file or directory"
                exit
            fi
        else
            echo "Error: You must specify a directory"
            exit
        fi
        ;;
	  --debug|-d)
        CMD="$CMD --debug"
        shift 1
		;;
      --nofork)
        CMD="$CMD --nofork"
        shift 1
        ;;
      --system|-s)
        CMD="$CMD --system"
        shift 1
        ;;
      --exit-with-session)
	    # exit-with-session implies nofork.
		CMD="$CMD --nofork"
        SESSION=$2
        if [ "x$(which $SESSION)" = "x" ];then
            echo "Error $2: Not a session"
            exit
        else
            echo $(which $SESSION)
            EXITWITH=yes
            shift 2
        fi
        ;;
      *)
            SESSION=$@ ; shift $#
        ;;
    esac
  done
echo "$CMD"

if [ "x$SESSION" = "x" ]; then
    # start normally
	exec $CMD
	exit $?
else

    if [ "x$EXITWITH" = "x" ]; then
	# we were passed a session to start
	#
	$CMD & ivmanpid=$!
	echo $DISPLAY
	$SESSION
	while ps $ivmanpid
	do
	    kill $ivmanpid || sleep 5
	done
	exit $?
    else
	# we were called with --exit-with-session, which means we
	# watch them and wait for them to die
	#
	exec $CMD & pid=$!
	KILLCMD="kill $pid && echo 'ivman killed' && exit"
	trap "eval $KILLCMD" ALRM HUP INT PIPE PROF TERM USR1 USR2 VTALRM ABRT

	while ps -C ivman -o pid --no-heading | grep -q $pid
	do
            if  ! ps -C $SESSION -o user | grep -q $USER
            then
		eval $KILLCMD
            fi
            sleep 5
	done
    fi
fi

