#!/bin/bash
#  $Id: activate 31792 2015-02-03 10:23:36Z mpetrov $
# -----------------------------------------------------------------------------
#  Name:    db:activate
#  Purpose: db specific installation steps by root
#
#  Note:    started from base:activate
#
#  env:     following variables are avaiable:
#           APL      APL_DB_DATA    HTTPD_CONF          TOMCAT_DIR TARGET_OS
#           APL_CONF APL_DB_USR     HTTPD_DIRS          TOMCAT_CFG DYLIB_SUFFIX
#           APL_USR  APL_HTTPD_GRP  HTTPD_MOD_DIR       TOMCAT_USR
#           APL_VAR  APL_HTTPD_USR  HTTPD_SHORT_MOD_DIR AXIS2_HOME
#  www:     module defined apache loc and dir should be placed in HTTPD_DIRS
# -----------------------------------------------------------------------------
#  Author: Alexei Titov
#  Edited by: Andrey Fomenko
#  QA by:  Christopher C Gettings
#  Copyright: videoNEXT LLC
# -----------------------------------------------------------------------------
[ $APL_ROLE = 'NODE' ] && exit 0;

PUSR=$APL_DB_USR

# --------  Section 0: SKMHA (linux) starts with clean DB space
if [ "$APL_MOD" = 'SKMHA' ]; then
  su $PUSR -lc "/usr/bin/pg_ctl stop -m immediate"
  [ -e "$APL_DB_DATA" ] &&  rm -rf $APL_DB_DATA
  # work around for new conditions
  /sbin/service postgresql initdb
  echo "local   all   all                            trust" >$APL_DB_DATA/pg_hba.conf
  echo "host    all   all      127.0.0.1/32          trust">>$APL_DB_DATA/pg_hba.conf
  /sbin/service postgresql start 
else 
  $APL/db/bin/db_restart     # the database is not running at this moment yet
fi
sleep 2

# --------  Section 1: Create APL db an
$APL/db/bin/db_create.pl skm_local
[ $? != 0 ] && exit 1

[ "$APL_MOD" = 'SKMHA' ] && exit 0  # SKMHA ends here

# --------  Section 3: Restart DB with new configuration
echo "host    all   all      10.8.0.0/24           trust  # connections from AVATAR via VPN">>$APL_DB_DATA/pg_hba.conf
$APL/db/bin/db_restart
sleep 2

# --------  Section 4: Define start/stop procedures
if [ $TARGET_OS != "Darwin" ]; then       #linux special steps
    systemctl enable postgresql 
fi

# APL actions
#su $APL_USR -c "$APL/db/bin/db_create_finalize"
mkdir -p $APL/var/db
chown $APL_USR $APL/var/db

exit 0
