#!/bin/sh
# PCP QA Test No. 1068
# Exercise pcp2zabbix.
#
# Copyright (c) 2015-2017 Red Hat.
#

seq=`basename $0`
echo "QA output created by $seq"

. ./common.python

$python -c "from pcp import pmapi" >/dev/null 2>&1
[ $? -eq 0 ] || _notrun "python pcp pmapi module not installed"
$python -c "from collections import OrderedDict" >/dev/null 2>&1
[ $? -eq 0 ] || _notrun "python collections OrderedDict module not installed"

which socat >/dev/null 2>&1 || _notrun "socat binary not installed"
which pcp2zabbix >/dev/null 2>&1 || _notrun "pcp2zabbix not installed"

status=1	# failure is the default!
signal=$PCP_BINADM_DIR/pmsignal
$sudo rm -rf $tmp $tmp.* $seq.full
trap "cd $here; rm -rf $tmp.*; exit \$status" 0 1 2 3 15

_seq_store()
{
    echo "--- pcp2zabbix stdout --" >>$seq.full
    cat $tmp.pcp2zabbix.out >>$seq.full
    echo "--- pcp2zabbix stderr --" >>$seq.full
    cat $tmp.pcp2zabbix.err >>$seq.full
    echo "--- socat stdout --" >>$seq.full
    cat $tmp.socat.out >>$seq.full
    echo "--- socat stderr --" >>$seq.full
    cat $tmp.socat.err >>$seq.full
}

_zbx_header()
{
    output=$1

    # extract the (partially binary) header, preceding the JSON response
    # and make it into a deterministic string
    sed -n 1p $output | \
    sed -e 's/{//g' | \
    od -c | \
    sed -n 1p | \
    sed -e 's/ D 001.*/ D/g'
}

zabbix_port=`_find_free_port`
log="--archive $here/archives/sample-secs"

# real QA test starts here
cat <<EOF >$tmp.config
[options]
zabbix_port = $zabbix_port
zabbix_host = HOSTNAME
zabbix_server = localhost
[globals]
secs = sample.seconds
msecs = sample.milliseconds
EOF

cat $tmp.config >>$seq.full

socat tcp-listen:$zabbix_port,reuseaddr - >$tmp.socat.out 2>$tmp.socat.err &
pid=$!
sleep 2
pcp2zabbix -r -t 2 -s 3 $log -c $tmp.config sample >$tmp.pcp2zabbix.out 2>$tmp.pcp2zabbix.err &   # will error out after socket cat dies
pmpid=$!
sleep 2
$signal $pid $pmpid 2>/dev/null
wait
_seq_store

echo "== Zabbix server input ==="
# check the first line has the initial ZBXD preamble (before JSON)
header=`_zbx_header $tmp.socat.out`
echo "header: $header"
echo "body:"
echo '{' # ate this from the header
sed -n '1!p' $tmp.socat.out
echo #}

# success, all done
status=0
exit
