#!/usr/bin/env sh
# Use sh to avoid having to install bash on virgin systems
err_env=1
ERR_NO_VENDOR=1002
ERR_NO_ZESK_BIN=1003

export PATH=$PATH:/usr/bin:/bin:/usr/local/bin

here=$(dirname "$0")
php=$(which php)
if [ -z "$php" ]; then
	echo "PHP is not found in PATH: " . $PATH 1>&2
	exit $err_env
fi
start=$(pwd)
app_root=
while [ -z "$app_root" ]; do
	current=$(pwd)
	if ls ./*.application.php 1> /dev/null 2>&1; then
		app_root=$(pwd)
	else
		cd ..
		next=$(pwd)
		if [ "$next" = "$current" ]; then
			break
		fi
	fi
done
cd "$start" || exit 1
if [ -z "$app_root" ]; then
	cd "$here" || exit $err_env
	cd .. || exit $err_env
	app_root=$(pwd)
	cd "$start" || exit $err_env
fi
for binary in "$app_root/bin/zesk-command.php" "$app_root/vendor/bin/zesk-command.php"; do
	if [ -x "$binary" ]; then
		exec "$php" "$binary" "$@"
	fi
done
if [ ! -d "$app_root/vendor/bin/" ]; then
	echo "No vendor directory exists, run: composer require zesk/zesk && composer install" 1>&2
	exit $ERR_NO_VENDOR
fi
echo "No zesk command file, run: composer require zesk/zesk && composer install" 1>&2
exit $ERR_NO_ZESK_BIN
