#! /bin/bash
# x3270 child script to send commands to pthvm1

#set -x
me=${0##*/}

# Make sure we're in the right environment.
if [ -z "$X3270INPUT" -o -z "$X3270OUTPUT" ]
then	echo >&2 "$me: must be run via the x3270 Script() action."
	exit 1
fi

# Verbose flag for x3270if
v=""

# Define some handly local functions.

# Common x3270 Ascii function
function ascii
{
	x3270if $v 'Ascii('$1')'
}

# Common x3270 String function
function string
{
	x3270if $v 'String("'"$@"'")'
}

# x3270 clear
function clear
{
	x3270if $v Clear
}

# x3270 enter
function enter
{
	x3270if $v Enter
}

# x3270 wait
function wait
{
	x3270if $v Wait
}

# x3270 readywait
function readywait
{
	ended="no"
	until [ "$ended" = "yes" ]
	do
	  if [ "$(ascii 61,140,7)" = "MORE..." ]
	  then
	    #x3270if $v "Info(\"clearing\")"
	    clear
	  fi
	  if [ $(ascii | grep "Ready" | wc -l) = 1 ]
	  then
	    #x3270if $v "Info(\"ended\")"
	    ended="yes"
	  fi
	  if [ "$ended" = "no" ]
	  then
	    #x3270if $v "Info(\"sleeping\")"
	    sleep 2
	  fi
	done
}

# x3270 cursor column
function cursor_col
{
	x3270if $v -s 10
}

# x3270 connection status
function cstatus
{
	x3270if $v -s 4
}

# Failure.
function die
{
	x3270if $v "Info(\"$me error: $@\")"
	x3270if $v "CloseScript(1)"
	exit 1
}

# Function to send a response back on the PTHVM1 child process pipe
function sndrsp
{
	echo "OK" > $ocp
}


# Make sure we're connected.
wait
[ "$(cstatus)" = N ] && die "Not connected."

# Set up pipe for receiving commands
icp=/tmp/pthvm1.x3270.pipe.in
rm -f $icp
mkfifo $icp

# Set up pipe for sending responses
ocp=/tmp/pthvm1.x3270.pipe.out
rm -f $ocp
mkfifo $ocp

# Send commands that appear in the pipe to the host
while [ 1 ]
do
  #x3270if $v "Info(\"Waiting for command\")"
  read command < $icp
  #x3270if $v "Info(\"command is $command\")"
  if [ "${command%%(*}" = "xfer" ]
  then
    # An x3270 file transfer request has been received
    parmstr=${command#*(}	#remove 'xfer(' from the beginning
    parmstr=${parmstr%)*}	#remove ')' from the end
    #x3270if $v "Info(\"parmstr is $parmstr\")"

    # Set default values for Transfer parameters
    Hostfile=""
    Localfile=""
    Direction="send"
    Host="tso"
    Mode="ascii"
    Exist="keep"
    Recfm="variable"
    Lrecl="1000"

    # Parse the Transfer parameters
    i=1
    parm=$(echo $parmstr | cut --delimiter=, --fields=$i)
    while [ "$parm" != "" ]
    do
      keywd=${parm%=*}
      value=${parm#*=}
      eval $keywd='"'"$value"'"'
      i=$(($i+1))
      parm=$(echo $parmstr | cut --delimiter=, --fields=$i)
    done
    # Execute the x3270 Transfer action
    x3270if $v "Transfer(\"Hostfile=$Hostfile\",\"Localfile=$Localfile\",\"Direction=$Direction\",\"Host=$Host\",\"Mode=$Mode\",\"Exist=$Exist\",\"Recfm=$Recfm\",\"Lrecl=$Lrecl\")"
    sndrsp
  else
    clear
    wait
    string "$command"
    enter
    readywait
    sndrsp
  fi
done

exit 0