#! /bin/sh
# PCP QA Test No. 258
# pmdatrace and libpcp_trace reconnect test
#
# Copyright (c) 2015 Red Hat.
# Copyright (c) 1995-2002 Silicon Graphics, Inc.  All Rights Reserved.
#

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

# get standard filters
. ./common.product
. ./common.check
. ./common.filter

[ -f $PCP_PMDAS_DIR/trace/pmdatrace ] || _notrun "trace pmda not installed"

signal=$PCP_BINADM_DIR/pmsignal
status=1
LOCALHOST=`hostname`
_needclean=true

_interrupt()
{
    status=1
}

if [ -d $PCP_LOG_DIR/pmlogger ]
then
    LOGGING_DIR=$PCP_LOG_DIR/pmlogger
else
    LOGGING_DIR=$PCP_LOG_DIR
fi

_cleanup()
{
    cd $here
    if $_needclean
    then
	pmafm $LOGGING_DIR/$LOCALHOST/Latest remove >$tmp.cmd 2>&1 \
	&& $sudo sh $tmp.cmd
	_service pcp restart 2>&1 | _filter_pcp_start
	_restore_auto_restart pmcd
	_wait_for_pmcd
	_wait_for_pmlogger
	if $install_on_cleanup
	then
	    ( cd $PCP_PMDAS_DIR/trace; $sudo ./Install </dev/null >/dev/null 2>&1 )
	else
	    ( cd $PCP_PMDAS_DIR/trace; $sudo ./Remove </dev/null >/dev/null 2>&1 )
	fi
	_needclean=false
    fi
    if [ -n "$savedtracehost" ]
    then
	PCP_TRACE_HOST=$savedtracehost; export PCP_TRACE_HOST
    fi
    rm -f $tmp.*
    exit $status
}

_change_config pmlogger on
_change_config pmcd on

install_on_cleanup=false
pminfo trace >/dev/null 2>&1 && install_on_cleanup=true

trap "_cleanup" 0
trap "_interrupt; _cleanup" 1 2 3 15

_stop_auto_restart pmcd

if [ -n "$PCP_TRACE_HOST" ]
then
    savedtracehost=$PCP_TRACE_HOST; unset PCP_TRACE_HOST
fi

# real QA test starts here

cd $PCP_PMDAS_DIR/trace
$sudo ./Install -R / </dev/null >/dev/null 2>&1
cd $here

cd $PCP_DEMOS_DIR/trace
$sudo $PCP_MAKE_PROG app2 >$tmp.make 2>&1
if [ $? -ne 0 ]
then
    echo app2 programs make failed.  Heres the make output ...
    cat $tmp.make
else
    echo make succeeded.
fi

# Allow app2 to reconnect asap
#
PCP_TRACE_RECONNECT=1
export PCP_TRACE_RECONNECT

( ( $PCP_DEMOS_DIR/trace/app2 >/dev/null 2>&1 & ) )
sleep 3
_service pcp restart 2>&1 | _filter_pcp_start
_wait_for_pmcd
_wait_for_pmlogger

# time_sucker transaction sleeps for 10 secs - wait for this
sleep 11
vals=`pminfo -f trace.transact.count | fgrep 'No value(s) available!' | wc -l`
if [ $vals -eq 1 ]
then
    echo "Error: No value(s) available!"
else
    echo "Reconnect succeeded."
echo
fi

$signal -a -s KILL app2 2>&1 >/dev/null

# xcheck observe problem where value of second observation of same tag
# gives first calls value.
echo
echo "=== Checking observed value matches latest call ==="
$here/src/obs
# these values are deteministic
pminfo -f trace.observe.count trace.observe.value

# success, all done
status=0
exit
