#! /bin/sh

# File:        squeak
# Author:      José L. Redrejo Rodríguez <jredrejo@edu.juntaextremadura.net>
#
# Carga la imagen de squeak que se le pasa como comando y si no
#se le pasa ninguna llama a squeak con la imagen preparada para LinEx
#
# Copyright (C) 2003 J.L.Redrejo.
#
# This file is free software; you can redistribute it and/or modify it
# under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it will be useful, but
# WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the GNU
# General Public License for more details.
#
#
#This script is for non-expert users to start Squeak easily.
#If the available arguments to start the squeak virtual machine have
#to be used, you should avoid using this script, and call the real
#virtual machine using squeakvm
#
#See squeakvm(1) for the virtual machine available arguments

set -e

# printf %q requires coretutils 8.25 or newer
if printf %q foo > /dev/null 2>&1; then
	SHELLQUOTE='printf %q\n'
else
	SHELLQUOTE='shell-quote --'
	echo 'printf too old, using shell-quote (CPAN String::ShellQuote) instead'
fi

findimages()
#first parameter: extension regex
#other parameters: lookup paths
{
	regex=$1
	shift
	find -L "$@" -maxdepth 1 -type f -name '*.image*' -print0 \
		| grep --null-data --perl-regexp --only-matching "([^/]+)(?=\\.(?:$regex))" \
		| sort --zero-terminated --unique \
		| xargs --null $SHELLQUOTE
}

pluginimage()
#first parameter: image file,
#second parameter: target directory
{
	#If the plugin exists
	if [ -f "$IMAGE_DIR/$1" ]; then
		#If it's not in the target directory, copy it
		if [ ! -f "$2/$1" ]; then
			cp "$IMAGE_DIR/$1" "$2/$1"
		#if it's in the target directory, but it's older, copy it:
		elif test "$IMAGE_DIR/${1}" -nt "${2}/${1}"; then
			cp "$IMAGE_DIR/$1" "$2/$1"
		fi
		#If it isn't in $HOME, do the right symbolic link:
		if [ ! -e ~/.npsqueak/"$1" ]; then
			ln -sf "$2/$1" ~/.npsqueak/"$1"
		fi
	fi
}

ensurefile()
{
	if [ ! -e "${2}" ]; then
		if [ -f "$1.bz2" ]; then
			source=${1}.bz2
			decompress=bunzip2
		elif [ -f "$1.gz" ]; then
			source=${1}.gz
			decompress=gunzip
		elif [ -f "$1" ]; then
			source=${1}
			decompress="cat"
		else
			source=""
		fi
	fi

	if [ -z "$source" ]; then
		# quietly do nothing if the source is not there;
		# this is used to support bare images that don't
		# have a changes file
		:
	else
		$decompress < $source > "$2"
	fi
}

PARAM1=$1
PARAM2=$2

#internationalization stuff:
if gettext.sh > /dev/null 2>&1; then
	. gettext.sh
	echo "found gettext in path"
else
	for n in "/usr" "/bin" "/usr/bin"; do
		if [ -e "${n}/gettext.sh" ]; then
			. ${n}/gettext.sh
			echo "found gettext in $n"
			break
		fi
	done
fi
if ! type eval_gettext > /dev/null 2>&1; then
	echo "FATAL! You don't have gettext.sh on your system."
	exit 1
fi

export TEXTDOMAINDIR=/usr/share/locale
export TEXTDOMAIN=squeak

message1=$(eval_gettext "There are several Squeak images")
message2=$(eval_gettext "Choose one:")

IMAGE_DIR=${SQUEAK_IMAGE_DIR:-/usr/share/squeak}

VM_VERSION=$(find /usr/lib/squeak/ -name "squeakvm" -type f | cut -f5 -d"/")
SQ_DIR=/usr/lib/squeak/$VM_VERSION

VM=${SQUEAK:-$SQ_DIR/squeakvm -mmap 1024M -nomixer }

first_parameter_is_project=''
case "$PARAM1" in
  *.pr)
	first_parameter_is_project=1
	;;
esac

if [ -z "$PARAM1" ] || [ -n "$first_parameter_is_project" ]; then
	mkdir -p ~/.squeak/"My Squeak"
	find -L "$IMAGE_DIR" -maxdepth 1 -name '*.sources' -exec ln -sft ~/.squeak/ '{}' +

	#create needed links to have squeak at $HOME:
	if [ ! -e ~/squeak ]; then
		ln -sf ~/.squeak ~/squeak
	fi

	#show all the images if there are more than one:
	eval set -- $(findimages 'image.*|gz|bz2' ~/squeak "${IMAGE_DIR}")

	if [ $# = 1 ]; then
		eval set -- $(findimages 'image.*|gz|bz2' ~/squeak)
		if [ $# = 1 ]; then
			eval set -- $(findimages 'image.*' ~/squeak)
			Archivo=$1
		else
			eval set -- $(findimages 'image.*' "${IMAGE_DIR}")
			Archivo=$1
		fi
		export SQUEAK_IMAGE="$HOME/squeak/$Archivo.image"
	else
		#let's find a dialog application to use:
		if [ -z "$DISPLAY" ]; then
			dialogo="whiptail"
		elif [ -n "$KDE_FULL_SESSION" ]; then
			dialogo="kdialog"
		else
			dialogo=$(which zenity || true)
			if [ -z "$dialogo" ]; then
				dialogo=$(which kdialog || true)
				if [ -z "$dialogo" ]; then
					dialogo="whiptail"
				else
					dialogo="kdialog"
				fi
			else
				dialogo="zenity"
			fi
		fi

		#now let's launch the dialog:
		if [ "$dialogo" = "zenity" ]; then
			Archivo=$(zenity --width=350 --height 250 --window-icon="/usr/share/pixmaps/squeak.png" --title "$message1" --list --column "$message2" "$@")
		else
			I=1
			for field in "$@"; do
				if [ $I = 1 ]; then
					set -- "$field" "$field"
				else
					set -- "$@" "$field" "$field"
				fi
				I=$((I+1))
			done
			file=$(mktemp)
			#
			if [ "$dialogo" = "kdialog" ]; then
				kdialog --title "${message1}" --menu "${message2}" "$@" --icon /usr/share/pixmaps/squeak.png > "$file"
			elif [ -z "$DISPLAY" ]; then
				whiptail --title "${message1}" --menu "${message2}" 20 80 10 "$@" --noitem 2> "$file"
			else
				x-terminal-emulator -e whiptail --title "$message1" --menu "$message2" 20 80 10 "$@" --noitem 2> "$file"
			fi
			Archivo=$(cat "$file")
		fi

		export SQUEAK_IMAGE="$HOME/squeak/$Archivo.image"
	fi #end of choosing the image to launch

	if [ -z "$Archivo" ]; then
		export SQUEAK_IMAGE=""
		exit
	fi

	if [ ! -f "$SQUEAK_IMAGE" ]; then
		ensurefile "$IMAGE_DIR/${Archivo}.image" "${SQUEAK_IMAGE}"
		if [ -f "$IMAGE_DIR/$Archivo.changes"* ]; then
			ensurefile "$IMAGE_DIR/${Archivo}.changes" ~/squeak/"$Archivo.changes"
		fi
	fi
else
	export SQUEAK_IMAGE=$PARAM1
fi

############## plugin configuration: #####################
mkdir -p ~/.npsqueak/secure
chmod 700 ~/.npsqueak/secure
mkdir -p ~/.npsqueak/untrusted
pluginimage "SqueakPlugin.image" ~/.npsqueak
pluginimage "EducarexPlugin.image" ~/.npsqueak
if [ ! -e ~/.npsqueak/SqueakPlugin.image ] && [ -e ~/.npsqueak/EducarexPlugin.image ]; then
	ln -sf ~/.npsqueak/EducarexPlugin.image ~/.npsqueak/SqueakPlugin.image
fi
###########################################################

#If Caps_Lock is active, we reset it
#xresetcapslock

if [ -z "$LC_ALL" ]; then
	export LC_ALL=$LANG
fi

#Si the user did not cancel, it starts:

if [ -n "$SQUEAK_IMAGE" ]; then
	if [ -z "$PARAM2" ]; then
		if [ -n "$first_parameter_is_project" ]; then
			case "$PARAM2" in
			  /*)
				$VM "$SQUEAK_IMAGE" "$PARAM1"
				;;
			  *)
				$VM "$SQUEAK_IMAGE" "$PWD/$PARAM1"
				;;
			esac
		else
			$VM
		fi
	else
		$VM "$PARAM1" "$PARAM2"
	fi
fi
