#!/bin/sh
# PCP QA Test No. 1161
# Exercise PCP netcheck PMDA dns modules - install, remove and values.
#
# Copyright (c) 2019 Red Hat.
#

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

. ./common.python

$python -c "from pcp import pmda" >/dev/null 2>&1
[ $? -eq 0 ] || _notrun "python pcp pmda module not installed"
$python -c "import importlib" >/dev/null 2>&1
[ $? -eq 0 ] || _notrun "python importlib module not installed"

[ -f $PCP_PMDAS_DIR/netcheck/Install ] || _notrun "netcheck PMDA not installed"

which ping >/dev/null 2>&1 || _notrun "ping not installed"
ping -c 1 localhost >/dev/null 2>&1 || _notrun "failed to ping localhost"

status=1       # failure is the default!
signal=$PCP_BINADM_DIR/pmsignal
$sudo rm -rf $tmp.* $seq.full

pmda_filter()
{
    sed \
	-e "s/.*Info:/Info:/g" \
	-e "s/\[.* or /\[X or /g" \
	-e "s/127.0.0.1,::1/OK/g" \
	-e "s/::1,127.0.0.1/OK/g" \
	-e "s/127.0.0.1/OK/g" \
	-e "s/::1/OK/g" \
	-e "s,value [0-9]*\.[0-9]*,value OK,g" \
	-e "s/value \"localhost.*/value \"LOCALHOST\"/" \
	-e "s/u'\([^']*\)'/'\1'/g" \
    #end
}

pmda_remove()
{
    echo
    echo "=== remove netcheck agent ==="
    $sudo ./Remove >$tmp.out 2>&1
    _filter_pmda_remove <$tmp.out
}

pmda_install()
{
    # start from known starting points
    cd $PCP_PMDAS_DIR/netcheck
    $sudo ./Remove >/dev/null 2>&1

    cat <<EOF >$tmp.config
[pmda]
modules = dns_lookup,dns_reverse
hosts = localhost
background_check = False
[dns_lookup]
timeout = 1
family = both
[dns_reverse]
timeout = 1
EOF
    echo "pmdanetcheck config:" >> $here/$seq.full
    cat $tmp.config >> $here/$seq.full

    [ -f $PCP_PMDAS_DIR/netcheck/netcheck.conf ] && \
    $sudo cp $PCP_PMDAS_DIR/netcheck/netcheck.conf $tmp.backup
    $sudo cp $tmp.config $PCP_PMDAS_DIR/netcheck/netcheck.conf

    echo
    echo "=== netcheck agent installation ==="
    $sudo ./Install < /dev/null >$tmp.out 2>&1
    cat $tmp.out | _filter_pmda_install | pmda_filter
}

pmda_cleanup()
{
    if [ -f $tmp.backup ]; then
        $sudo cp $tmp.backup $PCP_PMDAS_DIR/netcheck/netcheck.conf
        $sudo rm $tmp.backup
    else
        $sudo rm -f $PCP_PMDAS_DIR/netcheck/netcheck.conf
    fi
    # note: _restore_auto_restart pmcd done in _cleanup_pmda()
    _cleanup_pmda netcheck
}

_prepare_pmda netcheck
trap "pmda_cleanup; exit \$status" 0 1 2 3 15

_stop_auto_restart pmcd

# real QA test starts here
rm -f $tmp.stats
pmda_install
echo

echo "=== report metric values ==="
metrics=`pminfo netcheck | LC_COLLATE=POSIX sort`
pminfo -dfmtT $metrics 2>&1 \
| pmda_filter | tee -a $here/$seq.full

echo "=== verify metric values ==="
pminfo -v netcheck 2>&1 \
| pmda_filter | tee -a $here/$seq.full
pmda_remove

status=0
exit
