#!/bin/sh 

function ksdiff_executable_path() {
	# See where the system thinks ksdiff is
	ksdiff_exec=`which ksdiff`
	if [ ! $ksdiff_exec > /dev/null ] ; then
		# if which doesn't know where ksdiff is, check the default install location
		if [ -e '/usr/local/bin/ksdiff' ] ; then
			ksdiff_exec='/usr/local/bin/ksdiff'
		else
			if [ -L '/usr/local/bin/ksdiff' ] ; then
				echo "Could not resolve symlink to ksdiff" 1>&2
				exit 2
			else
				echo "Could not locate ksdiff" 1>&2
			fi
		fi
	fi
}

ksdiff_executable_path
if [ $ksdiff_exec > /dev/null ] ; then
	# Kaleidoscope 3.6 and later use a link from /usr/local/bin/ksdiff to ksdiff located in the Kaleidoscope app bundle.
	# If that link exists, installation is ok if the version matches. If /usr/local/bin/ksdiff is not a link,
	# it's outdated and needs to be updated.
	if [ -L $ksdiff_exec ] ; then
		# Check here for the version, but this fails in the Sandbox
		# because sandboxed ksdiff can not be launched from sandboxed Kaleidoscope,
		# it can't inherit the Kaleidoscope sandbox and wants its own sandbox, launching it
		# just crashes ksdiff.
		
		ks_bundle_version=$1
		echo Kaleidoscope version: $ks_bundle_version
		
		ks_is_sandboxed=$2
		echo Is sandboxed: $ks_is_sandboxed
		
		if [ $ks_is_sandboxed -eq 1 ] ; then
			exit 0
		else
			#not sandboxed also check the version
			short_version=`"$ksdiff_exec" --short-version`
			echo ksdiff version: $short_version

			if [[ $short_version == $ks_bundle_version ]] ; then
				exit 0
			else
				# May use a different exit code here? Exit code 2 is "Link Broken"
				echo "Version of ksdiff does not match" 1>&2
				exit 2
			fi
		fi
	else
		exit 210
	fi
else
	exit 1
fi
