#!/bin/sh 

if [ "$USER" != "postgres" ]; then
  echo "$0 must be run by postgres"
  exit
fi
echo "Initializing default data base by user $USER ..."

cd

PG_ROOT=/opt/pgsql
PATH=$PATH:$PG_ROOT/bin
PGLIB=$PG_ROOT/lib
PGDATA=$PG_ROOT/data
PGSHARE=$PG_ROOT/share
PGCERT=$PG_ROOT/apps/utils/cert
LD_LIBRARY_PATH=$PGLIB
export PATH PGLIB PGDATA LD_LIBRARY_PATH

if [ -d $PGDATA ]; then
    V=`cat $PGDATA/PG_VERSION`
    if [ "$V" = "8.3" ]; then
	echo "Version $V of database directory is already created."
	echo "Database directory $PGDATA is not initialized!!"
	exit
    else
	echo "Database directory $PGDATA is existed but is not a compatible version!"
	echo "Moving it to ${PGDATA}.bak!"
	echo "If you want to update database, dump and restore are required."
	mv -v $PGDATA  ${PGDATA}.bak
    fi
fi

initdb -L $PGSHARE -D $PGDATA --encoding=EUC_JP --no-locale -A trust

# create empty password file
touch $PGDATA/pg_pwd
chmod 600 $PGDATA/pg_pwd
### Option for 7.0
###cp $PGSHARE/pg_options.sample $PGDATA/pg_options
## SSL for 7.1 or up to 7.3
##cp $PGCERT/cert.pem $PGDATA/server.key
##cp $PGCERT/cert.cert $PGDATA/server.crt
# SSL for 7.4 or 8.0
HOST=`hostname -f`
# SSL for 8.1
if [ ".$HOST" = "." ]; then
  HOST=`hostname`
  if [ ".$HOST" = "." ]; then
    HOST=localhost
  fi
fi
sed -e "s/LOCALHOST/$HOST/" $PGCERT/mkrsakey.sh.template > $PGCERT/mkrsakey.sh
sh $PGCERT/mkrsakey.sh
mv $PGCERT/server.key $PGDATA/server.key
mv $PGCERT/server.crt $PGDATA/server.crt
chmod 600 $PGDATA/server.key $PGDATA/server.crt

# for client verification
#cp -p $PGDATA/server.crt $PGDATA/root.crt
#chmod 600 $PGDATA/root.crt
