#!/bin/sh
# PCP QA Test No. 1584
# Copyright (c) 2021 Red Hat.
#
# Exercise MongoDB agent Install and Remove scripts,
# plus metric value validation on select metrics.
#

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

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

MONGO_SHELL=`which mongo 2>/dev/null`
test -x "$MONGO_SHELL" || _notrun "MongoDB shell not installed"
test -d "$PCP_PMDAS_DIR/mongodb" || _notrun "MongoDB PMDA not installed"

MONGO_VERSION=`$MONGO_SHELL < /dev/null | grep 'server version' | awk '{ print $NF }'`
test -n "$MONGO_VERSION" || _notrun "MongoDB version not extracted"

_cleanup()
{
    cd $here
    $sudo rm -rf $tmp $tmp.*
}

status=1	# failure is the default!
$sudo rm -rf $tmp $tmp.* $seq.full
trap "_cleanup; exit \$status" 0 1 2 3 15

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

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

    echo
    echo "=== mongodb agent installation ==="
    $sudo ./Install </dev/null >$tmp.out 2>&1
    cat $tmp.out >>$here/$seq.full
    cat $PCP_LOG_DIR/pmcd/mongodb.log >>$here/$seq.full
    # Check mongodb metrics have appeared ... X metrics and Y values
    _filter_pmda_install <$tmp.out \
    | sed \
        -e 's/[0-9][0-9]* warnings, //' \
    | $PCP_AWK_PROG '
/Check mongodb metrics have appeared/   { if ($7 >= 20 && $7 <= 800) $7 = "X"
                                          if ($10 >= 0 && $10 <= 800) $10 = "Y"
                                        }
                                        { print }'
}

_prepare_pmda mongodb
# note: _restore_auto_restart pmcd done in _cleanup_pmda()
trap "_cleanup_pmda mongodb; exit \$status" 0 1 2 3 15

_stop_auto_restart pmcd

# real QA test starts here
pmdamongodb_install

echo "Check across all metrics for warnings on fetch"
pminfo -dft mongodb >> $here/$seq.full
pminfo -v mongodb

echo "Check server version value matches mongo shell"
pcpversion=`pmprobe -v mongodb.serverStatus.version | awk '{ print $NF }' | tr -d \"`
if [ $pcpversion = $MONGO_VERSION ]
then
    echo "Success - matching version numbers"
    status=0
else
    echo "Mismatch: $pcpversion vs $MONGO_VERSION" | tee -a $here/$seq.full
fi

pmdamongodb_remove
exit
