#!/bin/sh
# Author: Bert Freudenberg
# Modified by: John Maloney
# Purpose: Run Scratch using the Squeak virtual machine

echo "scratch-activity"
echo "$@"

echo "$0" "$@"
echo

# arguments are unordered, have to loop
args=""
while [ -n "$2" ] ; do
    case "$1" in
      	-b | --bundle-id)   bundle_id="$2"   ; args="$args BUNDLE_ID $2" ;;
      	-a | --activity-id) activity_id="$2" ; args="$args ACTIVITY_ID $2";;
      	-o | --object-id)   object_id="$2"   ; args="$args OBJECT_ID $2";;
	-u | --uri)         uri="$2"         ; args="$args URI $2";;
	*) echo unknown argument $1 $2 ;;
    esac
    shift;shift
done

# really need bundle id and activity id
if [ -z "$bundle_id" -o -z "$activity_id" ] ; then
  echo ERROR: bundle-id and activity-id arguments required
  echo Aborting
  exit 1
fi

# some debug output
echo launching $bundle_id instance $activity_id
[ -n "$object_id" ] && echo with journal obj $object_id
[ -n "$uri"       ] && echo loading uri $uri
echo

# do not crash on dbus errors
export DBUS_FATAL_WARNINGS=0

if [ -n "$object_id" ] ; then
	JOURNAL_DIR="$SUGAR_ACTIVITY_ROOT/data/Journal"
	mkdir -p "$JOURNAL_DIR"
	temp_filename="$JOURNAL_DIR/temp.sb"
	title=`copy-from-journal -o "$object_id" -m "$temp_filename" | grep "title "`
	# title is something like this for files downloaded from server:
	#       title -> File do_math_3.sb from http://schoolserver/Scratch/do_math_3.sb.
	# or like this if copied from USB flash drive:
	#       title -> do_math_3
	title=${title#*"title -> "} #cut off description
	echo "title: $title"

	# workaround for copy-from-journal bug (adds another dot before fileextension)
	if [ -f "$JOURNAL_DIR/temp..sb" ] ; then
		mv "$JOURNAL_DIR/temp..sb" "$temp_filename"
	fi

	if [[ "$title" == File*from* ]] ; then # for files downloaded from server
		filename=${title#*"File "} #cut off head until "File "
		filename=${filename%" from"*} #cut off tail from " from"
	        echo "filename: $filename"
        	full_filename="$JOURNAL_DIR/$filename"
        	echo "full_filename: $full_filename"
        	mv "$temp_filename" "$full_filename"
	else # for files from USB flash drive
		full_filename="$JOURNAL_DIR/$title.sb"
                echo "full_filename: $full_filename"
                mv "$temp_filename" "$full_filename"
	fi
else
	full_filename=""
fi
# run Squeak VM with Scratch image
exec /usr/bin/squeak \
	-vm-display-X11 \
	-swapbtn \
 	-sugarBundleId $bundle_id \
	-sugarActivityId $activity_id \
	ScratchXO.image \
	"$full_filename"
