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

set -e

base="$(dirname $0)"/git-annex-bundle

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

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

# Install busybox links.
if [ ! -e "$base/bin/sh" ]; then
	echo "(First run detected ... setting up busybox ...)"
	"$base/bin/busybox" --install "$base/bin"
fi

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

# Put our binaries first, to avoid issues with out of date or incompatable
# system or App binaries.
ORIG_PATH="$PATH"
export ORIG_PATH
PATH=$base/bin:$PATH
export PATH

ORIG_GIT_EXEC_PATH="$GIT_EXEC_PATH"
export ORIG_GIT_EXEC_PATH
GIT_EXEC_PATH=$base/libexec/git-core
export GIT_EXEC_PATH

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

# Indicate which variables were exported above.
GIT_ANNEX_STANDLONE_ENV="PATH GIT_EXEC_PATH GIT_TEMPLATE_DIR"
export GIT_ANNEX_STANDLONE_ENV

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