#!/bin/sh
# PCP QA Test No. 1589
# Exercise pcp2json HTTP POST functionality.
#
# Copyright (c) 2023-2024 Red Hat.  All Rights Reserved.
#


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"
$python -c "from http.server import BaseHTTPRequestHandler, HTTPServer" >/dev/null 2>&1
[ $? -eq 0 ] || _notrun "python import from http.server failed"

which pcp2json >/dev/null 2>&1 || _notrun "pcp2json not installed"
which nc >/dev/null 2>&1 || _notrun "nc binary not installed"
case `admin/whatami`
in
    *Slackware\ 15\.0*)
	    _notrun "nc -l does not work for me on Slackware 15.0"
	    ;;
    *MX\ 23\.2*)
	    _notrun "nc -l does not work for me on MX 23.2"
	    ;;
esac

_cleanup()
{
    cd $here
    $sudo rm -rf $tmp $tmp.*
}

status=0	# success is the default!
cpus=`pmprobe -v hinv.ncpu | awk '{print $3}'`
hostname=`hostname`
trap "_cleanup; exit \$status" 0 1 2 3 15

_filter_pcp2json_http()
{
    tee -a $seq_full \
    | col -b \
    | sed \
	-e "s/\(\"@host\"\): \""$hostname"\"/\1:HOST/g" \
	-e "s/\(\"value\"\): \""$cpus"\"/\1:NCPU/g" \
	-e 's/\(\"@timestamp\"\): \(.*\)/\1:DATE TIME/' \
	-e '/HTTP/d' \
    | LC_COLLATE=POSIX sort
} >> $tmp.python2.out

# real QA test starts here
port=`_find_free_port`
$PCP_PYTHON_PROG $here/src/pythonserver.py $port >$tmp.python.out 2>&1 &
pid=$!
sleep 2 # let server start up

echo "pcp2json invocation" | tee -a $seq_full
pcp2json -s1 -ZUTC -u http://localhost:$port hinv.ncpu >$tmp.json.out 2>$tmp.json.err

echo "pcp2json HTTP POST (sorted):"
_filter_pcp2json_http <$tmp.python.out
_check_http_filter <$tmp.python2.out

# terminate pythonserver.py now
pmsignal $pid >/dev/null 2>&1

echo "All diagnostics" >> $seq_full
for i in $tmp.json.out $tmp.json.err $tmp.python.out
do
    echo "=== $i ===" >>$seq_full
    cat $i >>$seq_full
done

echo "" | tee -a $seq_full

# success, all done
exit
