#!/bin/sh

exit_error () {
	echo "Error $1"
	if [ -z "${BS_DEBUG}" ] ; then
		sleep 5
		exit $1
	else
		echo "Debug mode, dropping to shell"
		exec /bin/sh ;
	fi
}

home_dir="$PWD"

tmp_dir="`mktemp -d`"
result=$?
if [ ${result} -ne 0 ] || [ ! -d "${tmp_dir}" ] ; then
	echo "Unable to create temporary directory."
	exit_error ${result}
fi

if [ -f /bin/asan_env.sh ]; then
	source /bin/asan_env.sh
fi

cd "${tmp_dir}"
/bin/media_bootstrap_tool /ConfigurationFiles/etc/bootstrap_initrd.config
result=$?
if [ ${result} -ne 0 ] ; then
	echo "Ramdisk bootstrap tool failed with ${result}" ;
	exit_error ${result}
fi

# Check if bootstrapped content contains new "autostart"
test -x "bin/autostart"
call_autostart=$?

# Prepare to move data, create all required directories
find . -type d -exec mkdir -p /{} \;
# Move everything else
find . ! -type d -exec mv -f {} /{} \;
result=$?
if [ ${result} -ne 0 ] ; then
	echo "Failed to move ramdisk contents" ;
	exit_error ${result}
fi

cd "${home_dir}"

#Cleanup
rm -rf "${tmp_dir}"

# Run autostart only if it was replaced with the new one during bootstrapping
if [ ${call_autostart} -eq 0 ]; then
	exec /bin/autostart "$@"
fi

exec /bin/product "$@"
