#! /bin/sh

# Create a new Pathena database under user's ownership.
# If $1 = new, assume there is a new database cluster available.
# Otherwise, remove any previous database instance first.
# Assumes postmaster already started on designated port.

# Home directory for Pathena files is changed in this script
# by invoking script 'build/relocate'.

export PATHENA=~/.pathena

if [ -e $PATHENA/config/definitions ];
    then DEFS=config ;
    else DEFS=bin ;
fi
source $PATHENA/$DEFS/definitions

cd $PATHENA

if [ $1 ]; then newflag=$1; else newflag=none; fi

if [ $newflag == new ]
    then echo "Creating a new Pathena database."
    else {
echo  "Creating a new Pathena database.
If one exists already it will be destroyed first.
If there are any open connections to the database,
they must be closed first or this operation will fail."

echo "
Deleting current database in 5 seconds.
If you want to abort, this would be an excellent time..."

sleep 5
$PGBIN/dropdb -p $PGPORT pathena
sleep 5   # pause to allow deletion to finish
}
fi

# Use default encoding assigned by Postgres cluster.
# (7.4: SQL_ASCII, 8.0: UNICODE)

#$PGBIN/createdb -p $PGPORT -E SQL_ASCII pathena

$PGBIN/createdb -p $PGPORT pathena

echo "Creating server languages."

$PGBIN/createlang -p $PGPORT plpgsql pathena
$PGBIN/createlang -p $PGPORT plpythonu pathena

# Tsearch2 built-in for version >= 7.4.  Will need to be installed
# for version 7.3.x.

echo "Processing SQL for dbsize module."
$PGBIN/psql -p $PGPORT -d pathena < $PGSHARE/contrib/dbsize.sql

echo "Processing SQL for tsearch2 module."
$PGBIN/psql -p $PGPORT -d pathena < $PGSHARE/contrib/tsearch2.sql

echo "Processing SQL for Pathena database schema."
$PGBIN/psql -p $PGPORT -d pathena < server/pathena.sql

build/add_stored_procs

echo "The Pathena database is ready.  If you are seeing this while
running the quick_install script, the client will be starting shortly.
Otherwise, you may start the client using the shell command
~/.pathena/bin/launch_client_pytk."
