#! /bin/bash

# File:        npsqueakrun
# Author:      Bert Freudenberg
# Last edited: 2005-02-28 18:42:20 by jens on impara.de
# Description: Script to start the Squeak VM binary 
#              from the Browser Plugin (npsqueak.so)
#              If necessary, sets up $HOME/.npsqueak/* first.

VM_VERSION=@VM_VERSION@
imgdir=@imgdir@

IMAGE=${imgdir}/SqueakPlugin.image
VM=squeak
VMOPTIONS=" -mmap 1024 -vm-display-x11 -swapbtn "
LOGFILE=/tmp/npsqueak.log

pdebug()
{
    if [ ! -z $NPSQUEAK_DEBUG ]; then 
	echo -e "npsqueak: $@" >> $LOGFILE 
    fi
}

perror()
{
    if [ ! -z $NPSQUEAK_DEBUG ]; then 
	echo -e "npsqueak error: $@" | tee -a $LOGFILE >&2 
    else
	echo -e "npsqueak error: $@"  >&2 
    fi
}

# is there a clever way to determine if you are local?
if [ $DISPLAY = ":0.0" ]; then
    VMOPTIONS=$VMOPTIONS" -xshm "
    pdebug "using x shared memory"
else
    pdebug "disabling x shared memory, because we are not local"
fi

if [ -e /usr/bin/squeakvm ]; then
    VM=squeakvm
fi

ensuredir()
{
    if [ ! -d "${1}" ] ; then
	if mkdir "${1}" ; then
	    pdebug "Created ${1}"
	    if [ -n "${2}" ] ; then
		chmod "${2}" "${1}"
	    fi
	else
	    perror "Could not create ${1}!"
	fi
    fi
}

ensurefile()
{
    if [ ! -e "${1}" ] ; then
	if cp "${2}" "${1}" ; then
	    pdebug "Created ${1}"
	else
	    perror "Could not create ${1}"
	    if [ ! -r "${2}" ] ; then
		perror "because ${2} is missing"
	    fi
	fi
    fi
}

ensureimage()
{
    if [ `dirname "${1}"` = "${HOME}/.npsqueak" ] ; then
	IMAGE=$1
    else
	IMAGE="${HOME}/.npsqueak/"`basename "$1"`
	ensurefile "$IMAGE" "$1" 
    fi 
}

ensure()
{
    if [ `dirname "${1}"` = "${HOME}/.npsqueak" ] ; then
	IMAGE=$1
    else
	IMAGE="${HOME}/.npsqueak/"`basename "$1"`
	ensurefile "$IMAGE" "$1" 
    fi 
}

if [ -e  "${HOME}/.npsqueak" ] ; then
    pdebug "don't create MySqueak link on desktop," 
    pdebug "because ${HOME}/.npsqueak exists"
else
    pdebug "create MySqueak link on desktop"
    ln -s "${HOME}/.npsqueak/My Squeak" "${HOME}/Desktop/My Squeak"
fi 

parameter_to_array(){
    i=0
    for p in "$@"; do
	i=$(( $i + 1 ))
	parameter[i]=$p
    done
}

ensuredir "${HOME}/.npsqueak" 
ensuredir "${HOME}/.npsqueak/secure" 700

if [ ! -z "$SQUEAK_USERDIR" ]; then
    pdebug "using SQUEAK_USERDIR"
    pdebug "My Squeak -> $SQUEAK_USERDIR"  
else
    pdebug "My Squeak -> ${HOME}/.npsqueak/My Squeak"
    ensuredir "${HOME}/.npsqueak/My Squeak"
fi

if [ -z "$1" ]; then
    pdebug "start squeak direct"
    ensureimage $IMAGE
    $VM $VMOPTIONS $IMAGE
else
    pdebug "start squeak from plugin"
    IMAGE="${6}"
    ensureimage $IMAGE
    parameter_to_array "$@"
    parameter[6]=$IMAGE
    $VM $VMOPTIONS "${parameter[@]}"
fi

