#!/bin/bash
# File:        etoys
# Author:      Bert Freudenberg
# Description: Script to start the Squeak VM binary 
#              with the etoys.image

VM="squeak"
VMOPTIONS="-encoding UTF-8 -vm-display-x11 -xshm"
IMAGE="@prefix@/share/etoys/etoys.image"
IMOPTIONS=""
DOCUMENT=""
WRAPPER=""

#set to 1 to work around OLPC bug #8008
export SQUEAK_FAKEBIGCURSOR=0

# if ETOYS_DEBUG is >= 1 do debug output
[ "0$ETOYS_DEBUG" -gt "0" ] && DEBUG=echo || DEBUG=false

# default directories (used if not running as Sugar activity)
[ -z "$SQUEAK_SECUREDIR" ] && export SQUEAK_SECUREDIR="$HOME/.etoys/private"
[ -z "$SQUEAK_USERDIR" ] && export SQUEAK_USERDIR="$HOME/Etoys"

[ ! -d "$SQUEAK_SECUREDIR" ] && mkdir -p "$SQUEAK_SECUREDIR" && chmod 700 "$SQUEAK_SECUREDIR"
[ ! -d "$SQUEAK_USERDIR" ] && mkdir -p "$SQUEAK_USERDIR"

function usage()
{
    echo "Usage: etoys [--param value] [-vmopt value] [arg value]"
    echo "       where --param is --vm, --image, or --document;"
    echo "       -vmopt is an option passed to the Squeak VM;"
    echo "       and args are passed to the Squeak image."
}

while [ -n "$1" ] ; do
	if [ -z "$2" ] ; then
	        usage
		exit -1
	fi
	case "$1" in
	        --help)
			usage
 			exit
			;;
	        --document)
			case "$2" in
			    /*) DOCUMENT="$2"
				;;
			    *) DOCUMENT="$PWD/$2"
				;;
			esac
 			shift
			;;
	        --image)
			case "$2" in
			    /*) IMAGE="$2"
				;;
			    *) IMAGE="$PWD/$2"
				;;
			esac
 			shift
			;;
	        --vm)
			case "$2" in
			    /*) VM="$2"
				;;
			    *) VM="$PWD/$2"
				;;
			esac
 			shift
			;;
		-*) VMOPTIONS="$VMOPTIONS $1 $2"
			shift
			;;
		*)  IMOPTIONS="$IMOPTIONS $1 $2"
			shift
			;;
	esac
	shift
done

# do not crash on dbus errors
export DBUS_FATAL_WARNINGS=0

# make Compose input methods work
[ -z "$LC_ALL" ] && export LC_ALL="$LANG"

# if pulseaudio is running, use it if VM has the driver, or fall back to OSS
if pulseaudio --check 2>/dev/null ; then
    if "$VM" -help 2> /dev/null | grep -q vm-sound-pulse ; then
        VMOPTIONS="$VMOPTIONS -vm-sound-pulse"
    else
        VMOPTIONS="$VMOPTIONS -vm-sound-oss"
        if padsp true 2>/dev/null ; then
            WRAPPER=padsp
        fi
    fi
fi

# enable compositioninput 
case "$LANG" in 
    bn* | gu* | hi* | kn* | ml* | mr* | ta* | te* | sa* )
        case "$LANG" in
            *.[uU][tT][fF]-8 | *.[uU][tT][fF]8)
                VMOPTIONS="$VMOPTIONS -compositioninput" 
                ;;
        esac
    ;;
esac

# VM, Image, and Document are non-optional
# Document has to be present even if empty for IMOPTIONS to work
$DEBUG $WRAPPER "$VM" $VMOPTIONS "$IMAGE" "$DOCUMENT" $IMOPTIONS
exec $WRAPPER "$VM" $VMOPTIONS "$IMAGE" "$DOCUMENT" $IMOPTIONS
