#!/bin/sh -e

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

#
# option analysis
#
init_only=false
database_name='daruma$devel'
db_access_command=psql

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

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

	--init-only)
		init_only=true
		;;

	--database)
		if [ $# -lt 2 ]; then
			usage 1>&2
			exit 1
		fi

		database_name="${2}"
		shift 1
		;;

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

	shift 1
done


#
# guess path of this program
#
#
# 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 command for acessing database
#
if ! which_command "${db_access_command}"; then
	echo "${db_access_command} 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)



check_postgres_user_exists()
{
	username=$1
	result=`psql -U pgsql postgres --tuples-only --no-align \
		-c "SELECT usename FROM pg_user WHERE usename='$1'"`

	if [ X"${result}" = X"${username}" ]; then
		return 0
	else
		return 1
	fi
}

check_postgres_database_exists()
{
	db_name="${1}"

	if psql -U pgsql postgres --tuples-only \
		--no-align --field-separator , -l \
	    | sed 's/^\([^,]*\),.*$/\1/' \
	    | fgrep "${db_name}" 1>/dev/null 2>&1; then
		return 0
	else
		return 1
	fi
}

##
## issue SQL commands
##
if [ ${init_only} != 'true' ]; then

	if ! check_postgres_user_exists daruma; then
		echo "creating user 'daruma' ..." 1>&2
		createuser -U pgsql --pwprompt \
			--no-superuser --createdb --no-createrole daruma
	fi

	if check_postgres_database_exists "${database_name}"; then
		dropdb -U daruma "${database_name}" 1> /dev/null
	fi

	createdb -U daruma ${database_name} 1> /dev/null
fi

if ! "${db_access_command}" -U daruma "${database_name}" -f postgis-setup/daruma-init.postgis 1>/dev/null 2>&1; then
	echo 1>&2
	echo "init failed" 1>&2
	exit 1
fi
