#!/bin/bash
# This file is part of Karabo.
#
# http://www.karabo.eu
#
# Copyright (C) European XFEL GmbH Schenefeld. All rights reserved.
#
# Karabo is free software: you can redistribute it and/or modify it under
# the terms of the MPL-2 Mozilla Public License.
#
# You should have received a copy of the MPL-2 Public License along with
# Karabo. If not, see <https://www.mozilla.org/en-US/MPL/2.0/>.
#
# Karabo is distributed in the hope that it will be useful, but WITHOUT ANY
# WARRANTY; without even the implied warranty of MERCHANTABILITY or
# FITNESS FOR A PARTICULAR PURPOSE.

SCRIPT=$(basename $0)
DEFAULT_DEFAULT=exfl-broker-1:5672
if [ -z $KARABO_BROKER ]; then
    BROKER_DEFAULT=$DEFAULT_DEFAULT
else
    # KARABO_BROKER is set, but might contain more than one URI.
    # So just use the first one, i.e. everything before the first ',':
    BROKER_DEFAULT=${KARABO_BROKER%%,*}
    # Then strip off the leading 'amqp://' to have e.g. exflbkr02n0.desy.de:5672:
    BROKER_DEFAULT=${BROKER_DEFAULT#amqp://}
fi

if [ ${#@} -le 0 ] || [ $1 == "-h" ] || [ $1 == "--help" ]; then
    # print help message if first argument asks for help
    echo
    echo "$SCRIPT - Look into messages stuck on broker:"
    echo
    echo "  $SCRIPT [-h|--help] topic [broker:port [numMessages [firstMessageIdx]]]"
    echo
    echo "Default broker:port is taken as first item in \$KARABO_BROKER if that is"
    echo "defined and is $DEFAULT_DEFAULT otherwise."
    echo
    echo "If numMessages is provided, the script will return the last numMessages messages"
    echo "in the index. Default is 1000"
    echo
    echo "If firstMessageIdx is provided, the script will return the numMessages messages"
    echo "starting from firstMessageIdx."
    echo
    echo "Needs karabo-querybroker as dependency."
    echo
    exit 0
fi

TOPIC=$1
# Broker from argument or from default if argument not set (or null).
BROKER=${2:-$BROKER_DEFAULT}
UNACK=$(karabo-querybroker -b $BROKER list dst | awk '$1 == "'$TOPIC'" {print $10} ')

# if inspecting an empty topic exit
if [ "$UNACK" -le 0 ]; then
    echo "No messages unacknowledged on Topic $TOPIC on broker $BROKER"
    exit 1
fi

# MAX_MSGS is the third variable. default is 1000
MAX_MSGS=${3:-1000}
# START_INDEX is the fourth variable.  default is UNACK-MAX_MSGS from the maximum (must be positive)
let "UNACK-=$MAX_MSGS"
START_INDEX=${4:-$UNACK}
if [ "$START_INDEX" -lt 0 ]; then
    START_INDEX=0
fi

OPT_MAX_MSGS="-maxMsgsRet $MAX_MSGS"
OPT_INDEX="-startMsgIndex $START_INDEX"

COMMAND="karabo-querybroker -b $BROKER list msg -t t -n $TOPIC -nocheck"
COMMAND="$COMMAND $OPT_INDEX $OPT_MAX_MSGS"

# Command gives something like:
# ...
#-----------------------------------------------------------------------------------
#Message #   Message IDs                                     Priority   Body Type
#-----------------------------------------------------------------------------------
#0           ID:15-192.168.140.159-59611-1459519722221       4          BytesMessage
#1           ID:8-192.168.140.159-59620-1459519722615        4          BytesMessage
# ...

IDS=''

while [ "$IDS" == '' ]
do
    UNACK=$(karabo-querybroker -b $BROKER list dst | awk '$1 == "'$TOPIC'" {print $10} ')
    if [ "$UNACK" -lt "$START_INDEX" ]; then
        echo "Topic freed up from the start of the script"
        exit 1
    fi
    IDS=$($COMMAND | grep 'ID:' | awk '{print $2}')
    echo -n "$(echo $IDS | wc -w) messages found ..."
done
echo 'Success'

declare -i counter=0

for msgID in $IDS
do
    echo "message query no. ${counter}: "
    karabo-querybroker -b $BROKER query msg -t t -n $TOPIC -nocheck -msgID $msgID
    echo
    echo "=================================================================="
    echo
    counter+=1
done
