#!/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`
$sudo rm -rf $tmp $tmp.* $seq.full
trap "_cleanup; exit \$status" 0 1 2 3 15

_filter_pcp2json_http()
{
    tee -a $here/$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' \
        -e "s/^\(Host: localhost\):$port/\1:PORT/g" \
        -e 's/^\(Content-Length:\) [1-9][0-9]*/\1 SIZE/g' \
        -e 's/^\(User-Agent: python-requests\).*/\1 VERSION/g' \
        -e 's/^\(Date:\).*/\1 DATE/g' \
        -e 's/\(\"context\":\) [0-9][0-9]*/\1 CTXID/g' \
        -e '/^Accept-Encoding: /d' \
        -e '/^Connection: keep-alive/d' \
        -e '/ using stream socket$/d' \
    | LC_COLLATE=POSIX sort
}

# 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 $here/$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

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

echo "All diagnostics" >> $here/$seq.full
for i in $tmp.json.out $tmp.json.err $tmp.python.out
do
    echo "=== $i ===" >>$here/$seq.full
    cat $i >>$here/$seq.full
done

echo "" | tee -a $here/$seq.full

# success, all done
exit
