#!/bin/sh -e

usage()
{
	echo "Usage: ${0} [option ...]"
	echo "Possible options are:"
	echo "  --help"
}

#
# option analysis
#
while [ "${#}" -gt 0 ]
do
	case "${1}" in

	--help)
		usage 1>&2
		exit 0
		;;

	*)
		usage 1>&2
		exit 1
		;;
	esac

	shift 1
done


#
# guess path of this program
#
get_my_dirname()
{
	my_filename=`basename $0`
	my_dirname=`dirname $0`

	if ! (echo "${my_dirname}" | grep '^/' >/dev/null); then
		if [ -x "${my_dirname}/${my_filename}" ]; then
			my_dirname=`cd ${my_dirname}; pwd`
		else
			for dir in `echo "${PATH}" | sed 's/:/ /g'`
			do
				if [ -x "${dir}/${my_filename}" ]; then
					my_dirname="${dir}"
					break
				fi
			done
		fi
	fi

	echo -n "${my_dirname}"
}


#
# replacement of `which' command for portability
#
which_command()
{
	command="${1}"

	for p in `echo "${PATH}" | sed 's/:/ /g'`
	do
		if [ -x "${p}/${command}" ]; then
			return 0
		fi
	done

	return 1
}


#
# check mysql command
#
if ! which_command mysql; then
	echo "mysql command not found, install it first" 1>&2
	exit 1
fi


#
# chdir to this program's directory
#
daruma_setup_path=`get_my_dirname`

cd "${daruma_setup_path}" \
	|| (echo "can't cd to ${daruma_setup_path}" 1>&2 ; exit 1)


#
# issue SQL commands
#
if ! mysql -u root -p < mysql-setup/daruma-unit-test-setup.mysql; then
	echo 1>&2
	echo -n "setup failed" 1>&2

	exit 1
fi
