#!/bin/bash
# This script was written by Daniele Favara <danjele@gmail.com>
CMD=ivman
CONFDIR=  # the config dir | null
EXITWITH=
SESSION=
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
        ;;
      *)
	  	#usage
		echo "---"
		echo "Error $1:  not a valid option"
		echo ""
	    echo "Usage: ivman-launch [OPTIONS]"
		echo "Please see 'man ivman-launch' for details."
		exit 1
        ;;
    esac
  done
echo "$CMD"

if [ "x$SESSION" = "x" ]; then
	exec $CMD
	exit $?
else
	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

