#!/bin/sh
[ -r conf ] && . ./conf
: ${PGDATA:="$PGROOT/data"}

if [ "$PGROOT" != "/var/lib/postgres" ]; then
	echo "Creating symlink /var/lib/postgres -> $PGROOT"

	ln -sf "$PGROOT" /var/lib/postgres
fi

if [ ! -d "/run/postgresql" ]; then
	echo "creating directory /run/postgresql"

	mkdir -p "/run/postgresql"
	chown -R postgres:postgres "/run/postgresql"
fi

if [ ! -d "$PGDATA" ]; then
	echo "Initializing database in $PGDATA"

	mkdir -p "$PGDATA"
	chown -R postgres:postgres "$PGDATA"
	chmod 0700 "$PGDATA"
	su - postgres -m -c "/usr/bin/initdb $INITOPTS -D '$PGDATA'" >/dev/null

	if [ -f /etc/postgresql/postgresql.conf ]; then
		ln -sf /etc/postgresql/postgresql.conf "$PGDATA/postgresql.conf"
	fi
fi

exec chpst -u postgres:postgres postgres -D "$PGDATA" $PGOPTS 2>&1
