#!/bin/sh

# install-imagej: Adds ImageJ capabilities to your OMERO installation.

set -e

# -- Subroutines --

die () {
	echo "$*" >&2
	exit 1
}

download () {
	name="$1"
	url="$2"
	dest="$3"
	echo "-> downloading $name"
	curl -fs "$url" > "$dest" || die "Failed to download: $url"
}

# -- Determine OMERO and ImageJ directories --

test $# = 1 ||
	die "Usage: $0 <path/to/omero> [--all]"

omero="$1"

test -f "$omero/lib/server/blitz.jar" ||
	die "Invalid OMERO installation: $omero"

if [ -e "$IMAGEJ_HOME" ]
then
	imagej="$IMAGEJ_HOME"
	echo "Using ImageJ location set by IMAGEJ_HOME: $imagej"
else
	imagej="$omero/lib/Fiji.app"
	echo "Using default location of ImageJ: $imagej"
fi

# -- Download and install ImageJ --

if [ -d "$imagej" ]
then
	echo "ImageJ installation already exists; skipping."
else (
	# Determine correct ImageJ launcher executable.
	case "$(uname -s),$(uname -m)" in
		Linux,x86_64) launcher=ImageJ-linux64 ;;
		Linux,*) launcher=ImageJ-linux32 ;;
		Darwin,*) launcher=Contents/MacOS/ImageJ-macosx ;;
		MING*,*) launcher=ImageJ-win32.exe ;;
		*) die "Unknown platform" ;;
	esac

	if [ ! -f "$imagej/fiji-nojre.zip" ]
	then
		echo
		echo "--> Downloading Fiji"
		(cd "$(dirname "$imagej")" &&
			curl -O http://downloads.imagej.net/fiji/latest/fiji-nojre.zip)
	fi

	echo
	echo "--> Unpacking Fiji"
	rm -rf "$imagej"
	(cd "$(dirname "$imagej")" && unzip fiji-nojre.zip)

	echo
	echo "--> Enabling ImageJ-OMERO"
	"$imagej/$launcher" --update add-update-site \
		OMERO-5.4 http://sites.imagej.net/OMERO-5.4
	"$imagej/$launcher" --update update-force-pristine
) fi

# -- Generate OMERO scripts --

gen_scripts="$imagej/lib/gen-scripts"

test -f "$gen_scripts" ||
	die "No script generator at: $gen_scripts"

echo "-> generating OMERO scripts"
"$gen_scripts" $@

echo
echo "To regenerate scripts, run:"
echo "    \"$gen_scripts\" \"$omero\" [--all]"