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

# Set the Informix env before running this script
# . /opt/informix/ol_informix.sh

path=`dirname $0`

if [[ $A4GL_SQLTYPE == pg* ]]; then
  # Postgres
  # The RPM install will have psql in the path
  sqlcmd=$(command -v psql)
  if [ -z "$sqlcmd" ]; then 
    sqlcmd="$path/../pgsql/bin/psql"
  fi
  sqlcmd="$sqlcmd -q -t -A"
  # Set serial values to 'default'
  catcmd="sed -e 's/0);/default);/' $path/menu-upd.sql" 
else
  # Informix
  sqlcmd=dbaccess
  catcmd="cat $path/menu-upd.sql"
  noheading='output to pipe "cat" without headings'
fi

# Check to make sure the menu item doesn't exist
doquery() {
row_exists=0

line=$($sqlcmd stansoft << SQL
  $noheading
  select 1 from menu_field where execline = '$value';
SQL
)

if [ "$line" ]; then # line is not null
  row_exists=$line
fi
}

# All new items need to be in menu-upd.sql as a cumulative update.
# Make sure to also add the menu items to menu.sql so when 
# creating a new database it will have all menu items. 

eval "$catcmd" | while read str
do
  # Get the *.4ge program name
  value=`echo "$str" | awk -F"'" '{print $8}'`
 
  # Make sure we've got the 4gl program name
  if [[ "$value" != *.4ge ]]; then
    continue
  fi
  doquery

if [ "$row_exists" == 0 ]; then
$sqlcmd stansoft << SQL
  $str
SQL
fi
done

# Give the superuser access to all menus
# Menu Maint gives access to user stansoft on new items
$sqlcmd stansoft << SQL
  delete from menu_secure where usercode = 'stansoft';
  insert into menu_secure select menu_field.itemlink, 'stansoft' from menu_field;
SQL

