#!/usr/bin/bash
# Copyright 2012-2023 Chad Lemmen http://www.lemmen.com
#
# Pilot Log startup script
#

function cleanup() {
  # Do not stop the database if there are other sessions open
  pidarr=($(pidof -x "$(basename $0)"))
  if [ "${#pidarr[@]}" -le 2 ]; then 
    pg_ctl stop 2>/dev/null
  fi
} 
trap cleanup SIGHUP EXIT

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

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

if ! [ -d "$AUBITDIR" ]; then
  if [ -d /usr/lib64/aubit4gl ]; then
    export AUBITDIR=/usr/lib64/aubit4gl
  else
    echo "You must set environment variable AUBITDIR"
    exit 1
  fi
fi

# Check PostgreSQL database server status
# pg_ctl exit status: 3=server not running, 4=cannot access data directory
pg_ctl status > /dev/null
ret=$?
if [ $ret -eq 3 -o $ret -eq 4 ]; then
  if [ $ret -eq 3 ]; then
    # Server is not running, start it...
    echo "Starting database server..."
    # setsid - run program in a new session otherwise it exits with this script
    #setsid pg_ctl -D "$ssdir"/data start
    # Let the server be killed on exit
    pg_ctl -o "-k $PGHOST" -D "$PGDATA" start > /dev/null
  fi

  # Make sure the database server is up, it can take a few seconds
  for i in {1..5}; do
    if [ $ret -eq 3 ]; then
      sleep 2
      pg_ctl status && break
      echo "Checking database status, attempt $i of 5"
      if [ $i -lt 5 ]; then
        continue
      fi
    fi

    echo
    echo "Failed to start the database, for details see"
    echo "$PGDATA/log"
    echo "If the problem is the port number, change PGPORT"
    echo "in $ssdir/etc/pilotlog.sh"
    echo
    echo "If this is a new install, run \"$ssdir/installpl\""
    echo "to initialize and create the database in directory"
    echo "$PGDATA"
    echo
    exit 1
  done
fi
  

# Set xterm title
echo -e "\033]2; Pilot Log \007"

menu.4ge MM

