#!/bin/bash

# squawk (simple queues using awk)
# 
# Author:  Andrew Birkett <andy@nobugs.org>
# Website: http://www.nobugs.org/developer/squawk
# Date:    10 May 2008
#
# Connects to an ActiveMQ broker using STOMP and consumes messages.
#
# Handler script is invoked with message body on stdin.  If it
# succeeds (exit code 0) then message is acknowledged.  Otherwise,
# message is available for retry.  Handler stdout/stderr will appears
# on our stderr (stdout is used for the network conversation)

if [[ $# != 4 ]]; then
  echo "Usage: consume stomphost stompport queuename handler"
  exit 1
fi

# Avoid escaping headaches and make this a self-contained script ..
awkfile=$(tempfile)
cat > $awkfile <<'EOF'
  BEGIN { 
    RS="\0"; ORS="\0"
    print "CONNECT\n\n"
    subscribe_str = ("SUBSCRIBE\ndestination:" queue "\nactivemq.prefetchSize:1\nack:client\n\n")
print subscribe_str
    fflush()
  }

  { 
    # ActiveMQ appear to use nul/lf as separator, so strip newline
    sub("^\n", "") 

    id = extract_msgid($0) 
    body = extract_body($0)

    if (id != "") {
      cmd = ( usercmd " >&2")
      print body | cmd;
      r = close(cmd);

      if (r == 0) {
        print "ACK\n" id "\n"
      } else {
        print ("UNSUBSCRIBE\ndestination:" queue "\n\n")
        system("sleep 1")
        print subscribe_str          
      }
      fflush()
    }
  }

  function extract_msgid(msg) {
    match(msg, "message-id:[[:graph:]]*\n", a)
    return a[0]
  }

  function extract_body(msg) {
    return substr( msg, match($0, "\n\n") + 2 )
  } 

EOF


# socat -v tcp4:$1:$2 SYSTEM:"awk --assign usercmd=$4 --assign queue=$3 -f $awkfile"
nc -c "awk --assign usercmd=$4 --assign queue=$3 -f $awkfile" $1 $2

