#!/bin/bash
# launcher script for Squeak Virtual Machine

VM_VER=3.9-10
PREFIX=${PREFIX:-/usr}

IMG_DIR=$PREFIX/lib/squeak
VM_LIBDIR=$PREFIX/lib/squeak/$VM_VER

VM=$VM_LIBDIR/squeak
VM_OPTS="-mmap 1024 -swapbtn"
VM_LOG=${TMPDIR:-/tmp}/squeak-$USER.log

SQUEAK_HOME=$HOME/squeak

test -x $VM || VM=$(which squeakvm || which squeak)

pickimage() {
	prompt="$1"
	imagefiles=$(/bin/ls *.image 2>/dev/null | grep -c \.image\$)
	if [ $imagefiles = 1 ]; then
		echo *.image
	elif [ -z "$DISPLAY" -o $imagefiles = 0 ]; then
		if [ ! -f $SQUEAK_HOME/squeak.image ]; then
			mkdir -p $SQUEAK_HOME
			gunzip -c $IMG_DIR/*.image.gz >$SQUEAK_HOME/squeak.image && \
				gunzip -c $IMG_DIR/*.changes.gz >$SQUEAK_HOME/squeak.changes
			ln -s SqueakV*.sources $SQUEAK_HOME
		fi
		test -f $SQUEAK_HOME/squeak.image && echo $SQUEAK_HOME/squeak.image
	elif dcop kdesktop >/dev/null; then
		# use KDE dialog
		kdialog --title "$prompt" --getopenfilename . \*.image
	else
		# fallback to GNOME dialog
		zenity --text "$prompt" --column "Squeak images" --list $(echo *.image)
	fi
}

#FIXME: pick plugin paths
VM_OPTS+=" -plugins $VM_LIBDIR"

# pick smart display options
if [ -n "$DISPLAY" ]; then
	host=${DISPLAY/%:*.*}
	VM_OPTS+=" -vm-display-X11"
	if [ -z "$host" -o "$host" = "localhost" -o "$host" = "127.0.0.1" ]; then
		VM_OPTS+=" -xshm"
	fi
elif [ -w /dev/fb0 ]; then
	VM_OPTS+=" -vm-display-fbdev"
else
	VM_OPTS+=" -vm-display-headless"
fi

# FIXME: pick smart sound options
VM_OPTS+=" -vm-sound-OSS"

for i in $*; do
	case "$i" in
		--) break ;;
		-*) VM_OPTS+=" $i"; shift ;;
		*) SQUEAK_IMAGE="$i"; shift; break ;;
	esac
done

# exit gracefully if the user chooses to cancel dialog

test -n "$SQUEAK_IMAGE" || SQUEAK_IMAGE=$(pickimage 'Choose an image file') || exit 0

echo exec $VM $VM_OPTS -- $SQUEAK_IMAGE $* | tee -a $VM_LOG

#exec $VM $VM_OPTS -- $SQUEAK_IMAGE $*
