#!/bin/sh

# Set the name of the executable here.
PROG=ROX-Menu
# The user might not have Python, so let's not make him install it.
if [[ ! -z `(python -V 2>&1) | grep '\([2-9].[2-9]..\)\|\(3.1..\)'` ]] 
then
	APP_DIR=`python -c 'import os.path, sys
apprun = os.path.realpath(sys.argv[1])
print os.path.dirname(apprun)' "$0"`
else
	APP_DIR=`dirname "$0"`
	APP_DIR=`cd "$APP_DIR";pwd`
fi
export APP_DIR
APP_NAME=`dirname "$0"`
APP_NAME=`basename "$APP_NAME"` ; export APP_NAME
EXEC_NAME=`basename "$0"`

if [ -z "$LD_LIBRARY_PATH" ]; then
	LD_LIBRARY_PATH=`$APP_DIR/rox_run ROX-CLib --runtime`
else
	LD_LIBRARY_PATH=`$APP_DIR/rox_run ROX-CLib --runtime`:$LD_LIBRARY_PATH
fi
export LD_LIBRARY_PATH

# Get choices path
if [[ $CHOICESPATH == '' ]] ; then
	CHOICES_DIR=$HOME/Choices/$APP_NAME
else
	# Get the first directory in CHOICESPATH
	CHOICES_DIR=`echo $CHOICESPATH | sed s/:.*//`
fi

ARCH=`uname -m`
case $ARCH in
	i?86) ARCH=ix86 ;;
esac

PLATFORM=`uname -s`-$ARCH
BIN="$APP_DIR/$PLATFORM"
DEBUGGER=""

# This is useful if you make symlinks of the program binary names in 
# your path and pointing them to the AppRun.
EXEC_FILE_PATH="$APP_DIR/$PLATFORM/$EXEC_NAME"
if [[ -x "$EXEC_FILE_PATH" && $EXEC_NAME != 'AppRun' ]] ; then
	exec "$EXEC_FILE_PATH" "$@"
elif [ $EXEC_NAME != 'AppRun' ] ; then
	echo "Unable to find $EXEC_NAME in binary directory." 
fi

case $1 in
	# Catch calls to other executables.
	# This is useful for general command-line use.
	--exec)
		EXEC_FILE_PATH="$APP_DIR/$PLATFORM/$2"
		if [ -x "$EXEC_FILE_PATH" ] ; then
			shift ; shift
			exec "$EXEC_FILE_PATH" "$@"
		else
			echo "Unable to find $EXEC_NAME in binary directory."
			echo "Use $0 --lsexec to list the existing binaries."
		fi
	;;
	# List the possible executables.
	--lsexec) ls "$APP_DIR/$PLATFORM" ;;
	# Let the user get at the Choices directory easily.
	--setup) rox $CHOICES_DIR ; exit 0 ;;
	# Delete the following if the application does not come with source.
	--debug) shift ; DEBUGGER=gdb ;;
	--compile)
		shift
		if [ ! -d "$APP_DIR/src" ] ; then
			echo "ERROR from $0:" >&2
			echo "Cannot compile - source code is missing!" >&2
			exit 1
		fi
		echo "Compiling $APP_DIR... please wait..." >&2
		if [ ! -x "$APP_DIR/src/configure" ]; then
		  echo "No 'configure' script! Trying to run autoconf..."
		  (cd "$APP_DIR/src"; autoconf)
		fi
		rm -f "$APP_DIR/src/config.cache"
		cd "$APP_DIR/src" \
			&& ./configure --bindir="$BIN" && make clean \
			&& make && make clean && echo Done >&2 && exit 0
		echo Compile failed >&2
		echo Press Return... >&2
		read WAIT
		exit 1
esac

BIN=$BIN/$PROG

if [ -x "$BIN" ]; then
  exec $DEBUGGER "$BIN" "$@"
else
  echo "ERROR from $0:" >&2
  echo "I cannot find an executable file for your host type ($PLATFORM)." >&2
  echo "Trying to compile..." >&2
  if [ -n "$DISPLAY" ]; then
    xterm -e "$0" --compile
  else
    "$0" --compile
  fi
  if [ -x "$BIN" ]; then
    exec "$BIN" "$@"
  fi
  exit 1
fi
