#!/usr/bin/bash
# Copyright 2012-2019 Chad Lemmen http://www.lemmen.com
#
# This file is part of Pilot Log.
#
# Pilot Log is free software: you can redistribute it and/or modify it under
# the terms of the GNU Affero General Public License as published by the Free
# Software Foundation, either version 3 of the License, or (at your option)
# any later version.
#
# Pilot Log is distributed in the hope that it will be useful, but WITHOUT
# ANY WARRANTY; without even the implied warranty of MERCHANTABILITY
# or FITNESS FOR A PARTICULAR PURPOSE. See the GNU Affero General Public
# License for more details.
#
# You should have received a copy of the GNU Affero General Public License
# along with Pilot Log. If not, see <https://www.gnu.org/licenses/>.
###############################################################################

ssdir=$(dirname $(realpath $0))
dbname=pilotlog

# Set the Aubit4GL and Postgres environment
. "$ssdir"/etc/pilotlog.sh

# The PostgreSQL data directory is not included in the
# package to ensure it is not clobbered by upgrades
# It will be created by initdb.

initdb -D "$PGDATA"
# database creation cannot be done as root, this will error if run as root
if [ $? -ne 0 ]; then
  exit 1
fi
# Enable the Postgres Log rotation
sed -i 's/#\(logging_collector =\) off/\1 on/' "$PGDATA"/postgresql.conf

# Startup database
postgres -k "$PGHOST" -D "$PGDATA" &
sleep 2

# Make sure the database server is up
for i in {1..5}; do
  pg_ctl status
  if [ $? -eq 3 ]; then
    # Server is not running, try again...
    echo "Attempt $i of 5"
    sleep 2
    if [ $i -eq 5 ]; then
      echo "Failed to start the database, see $PGDATA/log for details"
      echo "If the problem is the port number, change PGPORT"
      echo "in $ssdir/etc/pilotlog.sh"
      exit
    fi
  else
    break
  fi
done
   
psql -l "$dbname" >/dev/null 2>&1
if [ $? -eq 0 ]; then
  echo "Database already exists, exiting..."
  exit 1
fi

# Create the database
createdb -h "$PGHOST" "$dbname"
if [ $? -ne 0 ]; then
  exit 1
fi

# Load the database schema
psql "$dbname" <"$ssdir"/newdb/schema.sql

{
  echo "delete from menu_secure where usercode ='$LOGNAME';"
  echo "insert into menu_secure select itemlink,'$LOGNAME' from menu_field;"
} | psql "$dbname"

pg_ctl stop

# An rpm install will put this in /usr/bin
startup=$(which pilotlog)
if [ -z "$startup" ]; then
  startup="$ssdir/pl" 
fi

echo
echo
echo "Installation of Pilot Log complete."
echo
echo "To start the program run: $startup"
echo

