#!/bin/sh
#
#
#    Scalix Public License
#
#
#    The contents of this file are subject to the Scalix Public License
#    Version 1.1 ("License"); you may not use this file except in
#    compliance with the License. You may obtain a copy of the License at
#
# 
#    http://www.scalix.com/community/licensing 
#
# 
#    Software distributed under the License is distributed on an "AS IS"
#    basis, WITHOUT WARRANTY OF ANY KIND, either express or implied. See
#    the License for the specific language governing rights and limitations
#    under the License.
#
# 
#    The Original Code is Scalix Server. 
#    The Initial Developer of the Original Code is Scalix Corporation. 
#    Copyright (C) 2006 Scalix Corporation. 
#    All Rights Reserved.
#    Additional Copyrights may apply - see the notice in each file
#
#
#
#
#
#
# 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 $?
