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

# Check if this script is being called by a link 
linkname=`readlink $0`

if [ -n "$linkname" ]; then # is not null
  ssdir=`dirname "$linkname"`
else
  ssdir=`dirname $0`
fi

# 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"

export PATH=$PATH:$ssdir/bin

# Set Aubit environment
if [ `getconf LONG_BIT` = "64" ]; then
  #export AUBITDIR=$ssdir/aubit4gl64
  export AUBITDIR=$ssdir/aubit4gl
else
  export AUBITDIR=$ssdir/aubit4gl
fi
export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:$AUBITDIR/lib

# So forms and help file are found
export DBPATH=$DBPATH:$ssdir/bin


use_postgres()
{
# PostgreSQL
export A4GL_SQLTYPE=pg8
# Use libpq
#export A4GL_LEXTYPE=C
# Use libecpg
export A4GL_LEXTYPE=EC
export A4GL_LEXDIALECT=POSTGRES
export LD_LIBRARY_PATH=$ssdir/pgsql/lib:$LD_LIBRARY_PATH
export PGDATA=$ssdir/data
pgbin=$ssdir/pgsql/bin

# Make sure the Postgres database server is running
$pgbin/psql -l stansoft >/dev/null # we want errors to show

if [ $? -ne 0 ]; then
  echo "The PostgreSQL database server may not be running."
  echo "Start it by running $ssdir/etc/rc.postgresql start"
  echo
  echo "If you are using Informix then you must set INFORMIXDIR"
  echo "Example: export INFORMIXDIR=/opt/informix"
  exit
fi
}


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


use_informix()
{
# Set Informix environment
export LD_LIBRARY_PATH=$LD_LIBRARY_PATH:$INFORMIXDIR/lib:$INFORMIXDIR/lib/esql
. $INFORMIXDIR/ol_informix*.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

