#
# Common shell routines for testing the REST API daemon
# Copyright (c) 2014 Red Hat.
#

# get standard environment, filters and checks
. ./common.product
. ./common.filter
. ./common.check

unset http_proxy
unset HTTP_PROXY

_webapi_header_filter()
{
    tee -a $here/$seq.full \
    | col -b \
    | sed \
	-e 's/^\(Content-Length:\) [0-9][0-9]*/\1 SIZE/g' \
	-e 's/^\(Date:\).*/\1 DATE/g' \
	-e 's/\(\"context\":\) [0-9][0-9]*/\1 CTXID/g' \
	-e '/^Connection: Keep-Alive/d' \
    | LC_COLLATE=POSIX sort
}

_webapi_response_filter()
{
    tee -a $here/$seq.full \
    | col -b \
    | sed -e 's,#[0-9]*,####,g' \
        -e 's/ connected$//g' \
        -e '/^\* Adding handle: /d' \
        -e '/^\* Closing connection ####/d' \
        -e '/- Conn .*_pipe.*_pipe/d' \
        -e '/Curl_[\.a-zA-Z0-9]*:/d' \
        -e 's/::1/LOCALADDR/g' \
        -e 's/127\.0\.0\.1/LOCALADDR/g' \
        -e 's/PMWEBD error, .*/PMWEBD error, XXX/g' \
        -e 's/localhost[\.a-zA-Z0-9]*/LOCALHOST/g' \
        -e 's/Date:.*/Date: DATE/' \
	-e 's/\[[0-9][0-9]* bytes data]/[data not shown]/' \
        -e '/> User-Agent: /d' \
	-e '/Connection: Keep-Alive/d' \
    # end
}

_webapi_json_pretty()
{
    # python 2.6+:  python -mjson.tool
    # python 2.5-:
    python -c 'from simplejson.tool import main; main()' \
    | sed -e 's/, $/,/g'
}

_webapi_img_pretty()
{
    python -c "
import sys
from PIL import Image
from StringIO import StringIO
data = sys.stdin.read()
img = Image.open(StringIO(data))
print 'size=%dx%d\n' % (img.size[0], img.size[1])
"
}

_wait_for_pmwebd()
{
    webport=$1

    [ -z "$webport" ] && webport=44323

    count=0
    while ! $PCP_BINADM_DIR/telnet-probe -c localhost $webport
    do
	count=`expr $count + 1`
	if [ $count -ge 20 ]
	then
	    echo "pmwebd failed to start on port $webport"
	    status=1
	    exit
	fi
	pmsleep 0.1
    done
}

_wait_for_pmwebd_logfile()
{
    logfile="$1"

    sleep 2		# let it start up
    if [ -f "$logfile" ]
    then
	cat "$logfile" >>$here/$seq.full
    else
	echo "pmwebd failed to start, $logfile not created"
	$PCP_PS_PROG $PCP_PS_ALL_FLAGS | egrep '[P]ID|[p]mwebd'
	status=1
	exit
    fi
}

