#! /bin/sh

# Create a new PostgreSQL database cluster under user's ownership.
# Remove any previous database files first.
# Use entirely separate base directory and port number to avoid 
# interference with any existing databases.

# If $1 = install, this script is being called during installation.

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


echo "Creating a new PostgreSQL database cluster in subdirectory 'data'..."

# 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

rm -rf data/*   # Any existing cluster is removed first.

$PGBIN/initdb -D data

# Authorize client connections from localhost.

echo "
# Following lines added by Pathena installation script
# on $(date):

host    all         all         127.0.0.1         255.255.255.255   trust
" >> data/pg_hba.conf

# if [ $mode_flag != install ]
#     then {
# echo "
# # Following lines added by Pathena installation script
# # on $(date):

# redirect_stderr = true
# log_directory = '$PATHENA/log'
# log_filename = 'pg_stderr-%Y-%m-%d_%H%M%S.log'   # 'pg_stderr.log'

# log_line_prefix = '<%t> '
# " >> data/postgresql.conf

# #log_connections = true
# #log_disconnections = true
# }
# fi

# Start PostgreSQL server (postmaster) with local TCP/IP sockets enabled.

source $PATHENA/bin/pg_startup

echo "...database cluster has been created.
See log/pg_server for more details.
The PostgreSQL server daemon is up and running.
You may now proceed to create the Pathena database.
"
