#!/bin/sh
# File:            scratch
# Description:     Script to start the Cog Stack VM binary with the nuscratch image
# Original Author: Bert Freudenberg
# Adapted by:      Miriam Ruiz, Alex Bradbury, tim@Rowledge.org
# tim - trying to simplify a bit but good grief, shell script is incomprehensible

VM="/usr/bin/squeak"
IMAGE="/usr/share/scratch/NuScratch15012016.image"
IMOPTIONS=""
DOCUMENT=""
WRAPPER="sudo -E "
# prevent wiringPi from terminating  brutally
export WIRINGPI_CODES="TRUE"
#set to 1 to work around OLPC bug #8008
export SQUEAK_FAKEBIGCURSOR=0

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

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

[ ! -d "$HOME/Documents" ] && mkdir -p "$HOME/Documents"

usage()
{
    echo "Usage: scratch [--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."
}

if [ $# -eq 1 ] ; then
	case "$1" in
	    /*) DOCUMENT="$1"
		;;
	    *) DOCUMENT="$PWD/$1"
		;;
	esac
	shift
else
    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
fi
#test for likely camera setup, install v4l2 driver if needed
vcgencmd get_camera | grep -q 'supported=1 detected=1'
if [ $? -eq 0 ]; then
	sudo modprobe bcm2835-v4l2
fi

grep -q 'Sense HAT' /proc/device-tree/hat/product > /dev/null 2>&1
if [ $? -eq 0 ]; then
	sudo modprobe i2c-dev
fi

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