#!/bin/sh

if test -f /etc/sysconfig/postgresql; then
    . /etc/sysconfig/postgresql
else
    echo $"File \"/etc/sysconfig/postgresql\" not found."
    exit 1
fi

unset LANG

INIT_SET_PARAM=""
if [ ! -d "$PGDATA" ]; then
	mkdir -p "$PGDATA"
	chown postgres.postgres "$PGDATA"
fi
if [ -z "$PGLOCALE" ]
then
	locale_list="$(su -l postgres -s /bin/sh -c '/usr/bin/locale')"
	PGLOCALE="$(echo $locale_list | tr ' ' '\n' | grep LANG | cut -d '=' -f2 )"
fi
if [ -z "$PGMETHOD" ]
then
	PGMETHOD="scram-sha-256"
fi
if [ ! -z "$PGCHECK" ]
then
	INIT_SET_PARAM="$(echo $INIT_SET_PARAM -k)"
fi
if [ ! -z "$PGLOGDIR" ]
then
	INIT_SET_PARAM="$(echo $INIT_SET_PARAM --set log_directory=\"$PGLOGDIR\")"
fi
echo "Creating default database:"
su -s /bin/sh -l postgres -c "initdb  --pgdata=\"$PGDATA\" --locale=\"$PGLOCALE\" -A $PGMETHOD -W $INIT_SET_PARAM"
