#!/bin/bash
# Copyright 2011-2019 Chad Lemmen http://www.lemmen.com


# This works even if a link to this script is used
ssdir=$(dirname $(realpath $0))

# Set xterm title
echo -e "\033]2; Stansoft \007"
# Set xterm cursor color
# This makes the character under the cursor visible in reverse video
echo -ne "\033]12;Gray\007"


use_postgres() {
  # Set the PostgreSQL environment
  . "$ssdir"/etc/postgres.sh

  # Check for the PGDATA structure
  # only user stansoft can access the data directory from the shell
  #if ! [ -d "$PGDATA/base" ]; then
    # PGDATA does not exist. Warn the user to run install.
  #  echo "Directory \"$PGDATA\" is missing or empty."
  #  echo "Use \"$ssdir/install\""
  #  echo "to initialize and create the database."
  #  echo "See \"$ssdir/README\" for more information."
  #  exit 1
  #fi

  # Make sure the Postgres database server is running
  # pg_ctl: cannot be run as root
  # pg_ctl status >/dev/null
  psql -l >/dev/null # we want errors to show

  if [ $? -ne 0 ]; then
    echo
    echo "The PostgreSQL database server may not be running."
    echo "Start it by running \"$ssdir/etc/rc.postgresql start\""
    echo "or \"systemctl start stansoft\""
    echo
    echo "If you are using Informix then you must set INFORMIXDIR"
    echo "Example: export INFORMIXDIR=/opt/informix"
    echo
    echo "If this is a new install, use \"$ssdir/install\""
    echo "to initialize and create the database."
    echo "This will create the database in directory \"$PGDATA\""
    exit
  fi
}


getstate() {
  onstat -  >/dev/null 2>&1
  engine_state=$?
}


use_informix() {
  # Set Informix environment
  . $INFORMIXDIR/ol_informix*.sh
  . "$ssdir"/etc/stansoft.sh

  # Check that the database engine is up so the user knows right away
  # why it's not starting.
  #engine_up=$(onstat - | grep "Up" | wc -l)
  getstate
  if [ $engine_state != 5 ]; then
    echo "The database engine is down, to start it set the environment with"
    echo ". \$INFORMIXDIR/ol_informix.sh (make sure to include the dot space)"
    echo "then run: /opt/stansoft/etc/rc.informix start"
    exit
  fi
}


if [ -z "$INFORMIXDIR" ]; then
  use_postgres
else
  use_informix
fi

if [ -z "$SSMENU" ]; then
  # No menu set, default to the main menu
  SSMENU=MM
fi
menu.4ge $SSMENU

