#!/bin/sh

# this is a simple script wrapped by unixclient to access the adtec api on the command line.
# to use, set up an alias: alias cmd="unixclient /tmp/socket command.sh $*"
# call using syntax such as "cmd tra" or "cmd ipa" or "cmd mmo 1"

# exit code of zero (0) indicates success.  
# Errors may be reported on std out.

# TODO:  redirect error messages to stderr.
# TODO:  convert terse mode error numbers to exit codes


declare -i QUEST=0   # flag for indicated whether OK was responed
declare -i STATUS=1  # holds exit flag

echo "$*" >&7   # send the command to the api

while read -t 5 -u 6 -r LINE; do    # read the lines from the api
  if [[ $LINE = $'?\r' ]]; then 
     QUEST=1
     continue
  fi
  if [[ $LINE = $'\r' ]] && [[ $QUEST -eq 0 ]]; then 
     break
  fi
  if [[ $LINE = $'\r' ]] && [[ $QUEST -eq 1 ]]; then 
     continue
  fi
  if [ "$LINE" == $'OK\r' ] || [ "$LINE" = $'0\r' ]; then 
     QUEST=0
     STATUS=0
     continue
  fi

  echo "$LINE"   # display the result.
done
 
exit $STATUS

