#!/bin/sh -e
#
# 2011 Steven Armstrong (steven-cdist at armstrong.cc)
# 2021 Dennis Camera (dennis.camera at ssrq-sds-fds.ch)
#
# This file is part of cdist.
#
# cdist is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# cdist is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with cdist. If not, see <http://www.gnu.org/licenses/>.
#

quote() {
	for _arg
	do
		shift
		if test -n "$(printf '%s' "${_arg}" | tr -d -c '\t\n \042-\047\050-\052\073-\077\133\\`|~' | tr -c '' '.')"
		then
			# needs quoting
			set -- "$@" "'$(printf '%s' "${_arg}" | sed -e "s/'/'\\\\''/g")'"
		else
			set -- "$@" "${_arg}"
		fi
	done
	unset _arg

	# NOTE: Use printf because POSIX echo interprets escape sequences
	printf '%s' "$*"
}

postgres_user=$(cat "${__object:?}/explorer/postgres_user")

dbname=${__object_id:?}
state_should=$(cat "${__object:?}/parameter/state")
state_is=$(cat "${__object:?}/explorer/state")

if test "${state_should}" = "$state_is"
then
	exit 0
fi

case ${state_should}
in
	(present)
		set --

		while read -r param_name opt
		do
			if test -f "${__object:?}/parameter/${param_name}"
			then
				set -- "$@" "${opt}" "$(cat "${__object:?}/parameter/${param_name}")"
			fi
		done <<-'EOF'
		owner -O
		template --template
		encoding --encoding
		lc_collate --lc-collate
		lc_ctype --lc-ctype
		EOF

		set -- "$@" "${dbname}"

		cat <<-EOF
		su - $(quote "${postgres_user}") -c $(quote "$(quote createdb "$@")")
		EOF
		;;
	(absent)
		cat <<-EOF
		su - $(quote "${postgres_user}") -c $(quote "$(quote dropdb "${dbname}")")
		EOF
		;;
esac
