#!/bin/sh
#
# Initializes the database if not already initialized.
# Additionally, starts the database if not running.
#
# Usage: sxpsql-init
#

. /opt/scalix-postgres/bin/common-helpers.sh

if [ -f $PSQL_DIR/PG_VERSION ] ; then
    # database already initialized, nothing to do except starting it if not
    # running yet:
    /etc/init.d/scalix-postgres status >/dev/null || \
            /etc/init.d/scalix-postgres start
    exit 0
fi

# initialize the database:
su - -c "$PGENGINE/initdb -D $PSQL_DIR" postgres || exit $?

# then start it:
/etc/init.d/scalix-postgres start $INSTNAME || exit $?

# give it some time so that we don't get the
# "FATAL:  the database system is starting up" error from createdb:
sleep 3

# create the database:
su - -c "$PGENGINE/createdb -h $PSQL_DIR -p $PSQL_PORT -E UNICODE scalix" postgres || exit $?

# create "scalix" user:
if grep -q '^\(7\.\|8\.0\)' "$PSQL_DIR/PG_VERSION" ; then
    # versions prior to 8.1 didn't have --superuser flag
    create_flag="--adduser --no-createdb"
else
    # versions 8.1 and newer:
    create_flag="--superuser --no-createdb --no-createrole"
fi

su - -c "$PGENGINE/createuser -h $PSQL_DIR -p $PSQL_PORT $create_flag scalix" postgres || exit $?
