description "PostgreSQL - RDBMS server (version)"
author "Cameron Norman <camerontnorman@gmail.com>"

stop on (stop-postgresql-versions
         or deconfiguring-networking
         or unmounting-filesystem
         or runlevel [016])

instance $VERSION
usage "VERSION - version of PostgreSQL with corresponding config and binary"
export VERSION

pre-start script
    [ -d "/etc/postgresql/$VERSION" ] || exit 0
    [ "$(ls /etc/postgresql/$VERSION)" ] || exit 0
    [ -x "/usr/lib/postgresql/$VERSION/bin/postmaster" ] || exit 0

    ret=0
    for c in /etc/postgresql/"$VERSION"/*; do
	[ -e "$c/postgresql.conf" ] || continue
	name=$(basename "$c")

	# evaluate start.conf
	if [ -e "$c/start.conf" ]; then
	    start=$(sed 's/#.*$//; /^[[:space:]]*$/d; s/^\s*//; s/\s*$//' "$c/start.conf")
	else
	    start=auto
	fi
	[ "$start" = "auto" ] || continue

        initctl start postgresql-cluster VERSION=$VERSION CLUSTER=$name || ret=$?
    done
    exit $ret
end script

post-stop exec initctl emit stop-postgresql-clusters VERSION=$VERSION
