#! /bin/sh
# PCP QA Test No. 172
# Exercise $PMCD_PORT and $PMLOGGER_PORT mechanisms
#
# Copyright (c) 2014 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.filter
. ./common.check

which netstat >/dev/null 2>&1 || _notrun "netstat not installed"

rm -f $seq.out
_get_libpcp_config
if $ipv6 ; then
    ln $seq.out.ipv6 $seq.out || exit 1
else
    ln $seq.out.nonipv6 $seq.out || exit 1
fi

LOCALHOST=`hostname`
_needclean=true
status=0

_interrupt()
{
    status=1
}

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

_cleanup()
{
    if $_needclean
    then
	unset PMCD_PORT
	unset PMLOGGER_PORT
	pmafm $LOGGING_DIR/$LOCALHOST/Latest remove >$tmp.cmd 2>&1 \
	&& $sudo sh $tmp.cmd
	$sudo $PCP_RC_DIR/pcp restart | _filter_pcp_start
	_wait_for_pmcd
	_wait_for_pmlogger
	_needclean=false
    fi
    rm -f $tmp.*
    exit $status
}

pmafm $LOGGING_DIR/$LOCALHOST/Latest remove >$tmp.cmd 2>&1 \
&& $sudo sh $tmp.cmd

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

rm -f $seq.full

# real QA test starts here
PMCD_PORT=42000
PMLOGGER_PORT=43000
export PMCD_PORT PMLOGGER_PORT

echo "pmcd with PMCD_PORT=$PMCD_PORT, pmlogger with PMLOGGER_PORT=$PMLOGGER_PORT"
# need to do this indirectly because system sudo cleanses the environment
#
echo "export PMCD_PORT=$PMCD_PORT" >$tmp.start
echo "export PMLOGGER_PORT=$PMLOGGER_PORT" >>$tmp.start
echo "$PCP_RC_DIR/pcp restart" >>$tmp.start

$sudo sh $tmp.start | _filter_pcp_start
_wait_for_pmlogger -P $LOGGING_DIR/$LOCALHOST/pmlogger.log

echo
echo "pminfo with PMCD_PORT=$PMCD_PORT"
pminfo -v pmcd \
| sed -e '/^pmcd\.pmie/d'

echo
echo "pmlc with PMLOGGER_PORT=$PMLOGGER_PORT"
echo "show loggers" | pmlc \
| sed \
    -e '/primary/s/([0-9][0-9]*)/(LOGGER_PID) .../' \
    -e "s/on `hostname`/on HOST/" \
    -e "s/on local:/on HOST/" \
    -e 's/ *[0-9][0-9]*//g'

echo
echo 'port from $PCP_TMP_DIR/pmlogger/primary'
sed -e 1q $PCP_TMP_DIR/pmlogger/primary

# For Mac OS X need to massage lines like ..
# tcp4       0      0  *.42000                *.*                    LISTEN
# tcp6       0      0  *.42000                *.*                    LISTEN
#
echo "... and netstat"
netstat -an \
| tee -a $seq.full \
| sed -n -e '/4[23]000.*LISTEN/{
s/0\.0\.0\.0/inet/g
s/:::/inet6:/g
s/tcp4[ 0]*\*./inet./
s/tcp6[ 0]*\*./inet6./
s/:/./g
s/.*\(inet6*.4[23]000\).*\(LISTEN\).*/... \1 ... \2/
p
}' \
| sort
