#!/bin/sh
########################################################################
# runwithx - Shell script to start X11-based Vrui applications under
# Mac OS X with a private X server to get full-screen control.
# Copyright (c) 2006-2007 Oliver Kreylos and Braden Pellett
#
# This file is part of the Vrui Runtime Environment.
# 
# The Vrui Runtime Environment is free software; you can redistribute it
# and/or modify it under the terms of the GNU General Public License as
# published by the Free Software Foundation; either version 2 of the
# license, or (at your option) any later version.
#  
# The Vrui Runtime Environment is distributed in the hope that it will
# be useful, but WITHOUT ANY WARRANTY; without even the implied warranty
# of MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
# General Public License for more details.
# 
# You should have received a copy of the GNU General Public License
# along with the Vrui Runtime Environment; if not, write to the Free
# Software Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA
# 02111-1307 USA
########################################################################

# Init local variables
xinitrc="_VRUIETCDIR_/Vrui.xinitrc"
vrDeviceDaemon="_VRUIBINDIR_/VRDeviceDaemon"
currDir="$PWD"
homeDir=.
goToProgDir=0
prog=

# Remove a -c <dir> argument from the command line
if [[ $1 == '-c' ]] ; then
	if [[ $# -ge 2 ]] ; then
		homeDir="$2"
		shift
		shift
	else
		shift
	fi
fi

# Remove a -d argument from the command line
if [[ $1 == '-d' ]] ; then
	goToProgDir=1
	shift
fi

# Print usage if no executable is given
if [[ $# -eq 0 ]] ; then
	echo "usage: $0 [-c directory] [-d] executable [arguments]"
	echo "       Run executable in a basic X windows environment using xinit."
	echo "       -c <directory> will change to the given directory before running"
	echo "                      the executable."
	echo "       -d run the given executable from its directory."
	exit 1
fi

# Remember and remove the executable name
prog="$1"
shift
if [[ goToProgDir -ne 0 ]] ; then
	homeDir=$(dirname "$prog")
fi

# Set up trap in case user exits the script
# instead of the X application
progName=$(basename $prog)
trap "killall $progName ; killall X" EXIT

# Run the executable
cd $homeDir
if [[ -e $prog ]] ; then
	export PATH=$PATH:/usr/X11R6/bin
	xinit "$xinitrc" "$currDir/$homeDir" "$prog" $*
else
	echo "Cannot find $prog"
fi
