#! /bin/zsh
#
#   41postinstall
#

set -u
progname=`basename $0`;
echo "### $progname ###"
buildenv=../buildenv
if [ ! -r $buildenv ]; then
    echo "$progname: $buildenv not found" >&2
    exit 1;
fi
. ../buildenv
APPDIR=${POSTGRESQL}

cd ${APPDIR}

create_user() {
    _username=$1;
    id ${_username} >/dev/null 2>&1
    if [ $? -ne 0 ]; then
    /usr/sbin/adduser ${_username}
    fi
    bash_profile=~${_username}/.bash_profile
    lc=0;
    if [ -f ${bash_profile} ]; then
    lc=`grep "POSTGRES_HOME=/usr/local/pgsql-8.1.3" $bash_profile | wc -l`
    else
    touch $bash_profile;
    fi
    if [ ${lc} -lt 1 ]; then
    cat >> $bash_profile << EOD
export PATH=\$PATH:/usr/local/pgsql-8.1.3/bin
export POSTGRES_HOME=/usr/local/pgsql-8.1.3
export PGLIB=\$POSTGRES_HOME/lib
export PGDATA=\$POSTGRES_HOME/data
export MANPATH="\$MANPATH":\$POSTGRES_HOME/man
export LD_LIBRARY_PATH="\$LD_LIBRARY_PATH":"\$PGLIB"
EOD
    fi
}

create_user postgres
create_user testuser

if [ ! -d /usr/local/${POSTGRESQL}/data ]; then
    mkdir -p /usr/local/${POSTGRESQL}/data
    chown postgres /usr/local/${POSTGRESQL}/data
fi
	
lc=`ls -1 /usr/local/postgresql-8.1.3/data | wc -l`
if [ ${lc} -lt 1 ]; then
    sudo -u postgres /usr/local/${POSTGRESQL}/bin/initdb -D /usr/local/${POSTGRESQL}/data
    test $? -eq 0 || exit 1;
    sudo -u postgres /usr/local/${POSTGRESQL}/bin/postmaster -D /usr/local/${POSTGRESQL}/data >logfile 2>&1 &
    test $? -eq 0 || exit 1;
    sleep 5;
    sudo -u postgres /usr/local/${POSTGRESQL}/bin/createdb test
    test $? -eq 0 || exit 1;
    sudo -u postgres /usr/local/${POSTGRESQL}/bin/createuser -d -a testuser
    test $? -eq 0 || exit 1;
    #sudo -u postgres /usr/local/${POSTGRESQL}/bin/psql test
    #test $? -eq 0 || exit 1;
    killall -TERM postmaster
fi

exit 0;
