#!/bin/sh
# Runs a shell command (or interactive shell) using the binaries 
# bundled with this app.

set -e

orig_IFS="${IFS}"
unset IFS

base="$(dirname "$0")"

if [ ! -d "$base" ]; then
	echo "** cannot find base directory (I seem to be $0)" >&2
	exit 1
fi

bundle="$base/bundle"

if [ ! -e "$bundle/git-annex" ]; then
	echo "** bundle directory $bundle does not contain git-annex" >&2
	exit 1
fi
if [ ! -e "$bundle/git" ]; then
	echo "** bundle directory $bundle does not contain git" >&2
	exit 1
fi

# Get absolute path to base, to avoid breakage when things change directories.
orig="$(pwd)"
cd "$base"
base="$(pwd)"
cd "$orig"

# Install shim that's used to run git-annex-shell from ssh authorized_keys.
# The assistant also does this when run, but the user may not be using the
# assistant.
if [ ! -e "$HOME/.ssh/git-annex-shell" ]; then
	mkdir "$HOME/.ssh" >/dev/null 2>&1 || true
	if [ -e "$HOME/.ssh" ]; then
		(
			echo "#!/bin/sh"
			echo "set -e"
			echo "if [ \"x\$SSH_ORIGINAL_COMMAND\" != \"x\" ]; then"
			echo "exec '$base/runshell' git-annex-shell -c \"\$SSH_ORIGINAL_COMMAND\""
			echo "else"
			echo "exec '$base/runshell' git-annex-shell -c \"\$@\""
			echo "fi"
		) > "$HOME/.ssh/git-annex-shell.$$"
		chmod +x "$HOME/.ssh/git-annex-shell.$$"
		mv "$HOME/.ssh/git-annex-shell.$$" "$HOME/.ssh/git-annex-shell"
	fi
fi

# And this shim is used by the webapp when adding a remote ssh server.
if [ ! -e "$HOME/.ssh/git-annex-wrapper" ]; then
	mkdir "$HOME/.ssh" >/dev/null 2>&1 || true
	if [ -e "$HOME/.ssh" ]; then
		(
			echo "#!/bin/sh"
			echo "set -e"
			echo "exec '$base/runshell' \"\$@\""
		) > "$HOME/.ssh/git-annex-wrapper.$$"
		chmod +x "$HOME/.ssh/git-annex-wrapper.$$"
		mv "$HOME/.ssh/git-annex-wrapper.$$" "$HOME/.ssh/git-annex-wrapper"
	fi
fi

# Put our binaries first, to avoid issues with out of date or incompatible
# system binaries. Extra binaries come after system path.
ORIG_PATH="$PATH"
export ORIG_PATH
PATH="$bundle:$PATH:$bundle/extra"
export PATH

ORIG_GIT_EXEC_PATH="$GIT_EXEC_PATH"
export ORIG_GIT_EXEC_PATH
GIT_EXEC_PATH="$bundle/git-core"
export GIT_EXEC_PATH

ORIG_GIT_TEMPLATE_DIR="$GIT_TEMPLATE_DIR"
export ORIG_GIT_TEMPLATE_DIR
GIT_TEMPLATE_DIR="$bundle/templates"
export GIT_TEMPLATE_DIR

GIT_ANNEX_DIR="$bundle"
export GIT_ANNEX_DIR

# Indicate which variables were exported above and should be cleaned
# when running non-bundled programs.
GIT_ANNEX_STANDLONE_ENV="PATH GIT_EXEC_PATH GIT_TEMPLATE_DIR"
export GIT_ANNEX_STANDLONE_ENV

if [ -n "${orig_IFS}" ]; then
	IFS="${orig_IFS}"
	export IFS
fi

if [ "$1" ]; then
	cmd="$1"
	shift 1
	exec "$cmd" "$@"
else
	$SHELL
fi
