#!/bin/sh
# *********************************************************************
# * Licensed materials - Property of IBM                              *
# *     UrbanCode Deploy                                              *
# * (c) Copyright IBM Corporation 2011, 2014. All Rights Reserved.    *
# * (c) Copyright HCL Technologies Ltd. 2022. All Rights Reserved.    *
# * US Government users restricted rights  -  Use, duplication or     *
# * disclosure restricted by GSA ADP schedule contract with IBM Corp. *
# *                                                                   *
# *********************************************************************
# *
# * This shell script is used to invoke the ISPF Gateway
# *
# * BUZ_CFG must be set to the configuration directory. The directory
# * contains ISPF.conf, buzenv.sh and other configuration files to
# * run the UrbanCode Deploy z/OS toolkit
# *********************************************************************
#
# run buzenv.sh to set environment variables
SHELL_PATH=$1

if [ "." = "$SHELL_PATH" ]
then
   SHELL_PATH=`pwd`
fi
setenvzosfile="$SHELL_PATH/setenv-zos.sh"
if [ -r "$setenvzosfile" ]; then
   . $setenvzosfile 2>&1
else 
  if [ -z "$BUZ_CFG" ]; then
    echo ERROR -- Please run the command from the Agent bin directory. 
    exit 16
  else 
    if [ ! -r $BUZ_CFG/setenv-zos.sh ]; then
      echo ERROR -- $BUZ_CFG/setenv-zos.sh does not exist or cannot be read
      echo ls -l $BUZ_CFG/ 2>&1
      ls -l $BUZ_CFG/ 2>&1
      echo
      exit 16
    else
      . $BUZ_CFG/setenv-zos.sh 2>&1  
    fi 
  fi
fi

LOG_ISPF=$ISPF_LOG_DIR/LOGISPF.$$

echo "<?xml version=\"1.0\"?>
<ISPF-INPUT>
<SERVICE-REQUEST>
<service>ISPF</service> 
<session>NONE</session>
<command>TSO EX '$2' '$3 \"$4\" \"$5\" \"$6\" \"$7\" \"$8\" \"$9\" \"${10}\" \"${11}\" \"${12}\" \"${13}\" \"${14}\" \"${15}\" \"${16}\"'</command>
</SERVICE-REQUEST>
</ISPF-INPUT>" | ISPZXML >$LOG_ISPF
rc=0
grep "The initially invoked CLIST ended with a return code =" $LOG_ISPF >/dev/null
if [ $? -eq 0 ]
then
        rc=1
else
        grep "<RETURN-CODE>" $LOG_ISPF >/dev/null
        if [ $? -eq 0 ]
        then
                # Check RETURN CODE
        a=`sed -n -e 's/<RETURN-CODE>\(.*\)<.*/\1/p' $LOG_ISPF | sed -e '1 q'`
        if test $a != 0
        then
                rc=3
        fi
    else
        echo "The ISPF gateway is not configured correctly."
        rc=2
    fi
fi
if [ $rc -gt 1 ]
then
        cat $LOG_ISPF
else
        ispfout=0
        cat $LOG_ISPF | while read line
        do
                if [ "]]>" = "$line" ]; then break; fi
                if [ $ispfout -eq 1 ]; then echo "$line"; fi
                if [ "<![CDATA[" = "$line" ]; then ispfout=1; fi
        done
fi

rm $LOG_ISPF
exit $rc