#!/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_real_own_dirname()
{
	own_filename=`basename $0`
	own_dirname=`dirname $0`

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

	if [ -L "${own_dirname}/${own_filename}" ]; then
		dirname `readlink "${own_dirname}/${own_filename}"`
	else
		printf '%s' "${own_dirname}"
	fi
}


#
# 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_real_own_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 "setup failed" 1>&2

	exit 1
fi
