#!/bin/sh
# PCP QA Test No. 682
# Exercise MMV v3 labels support under valgrind.
#
# Copyright (c) 2018 Red Hat.
#

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

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

[ "$(id -un)" = root ] && _notrun "this test fails if run as root"

_check_valgrind

status=1
username=`id -u -n`
hostname=`hostname`
machineid=`_machine_id`
domainname=`_domain_name`
MMV_STATS_DIR="$PCP_TMP_DIR/mmv"

_cleanup()
{
    cd $here
    if $need_restore
    then
	need_restore=false
	$sudo rm -rf $PCP_ETC_DIR/pcp/labels/*
	_restore_config $PCP_ETC_DIR/pcp/labels
	[ -d $MMV_STATS_DIR.$seq ] && _restore_config $MMV_STATS_DIR
	_sighup_pmcd
    fi
    $sudo rm -rf $tmp $tmp.*
}

trap "_cleanup; exit \$status" 0 1 2 3 15

need_restore=true
_save_config $PCP_ETC_DIR/pcp/labels
$sudo rm -rf $PCP_ETC_DIR/pcp/labels/*

# real QA test starts here
home="$PCP_PMDAS_DIR"
iam=mmv

# move the MMV directory to restore contents later.
[ -d $MMV_STATS_DIR ] && _save_config $MMV_STATS_DIR

# create a directory we can write and pcp group can read
$sudo rm -rf "$MMV_STATS_DIR"
$sudo mkdir -m 755 "$MMV_STATS_DIR"
$sudo chown $username "$MMV_STATS_DIR"
$sudo chgrp pcp "$MMV_STATS_DIR"

_filter_paths()
{
    sed \
	-e "s,$here,QADIR,g" \
	-e "s,$PCP_TMP_DIR,PCP_TMP_DIR,g" \
	-e "s,$PCP_PMDAS_DIR,PCP_PMDAS_DIR,g" \
    #end
}

_run_valgrind $here/src/mmv3_labels | _filter_paths

_filter_mmvdump()
{
    sed \
	-e "s,^Process.*= [0-9][0-9]*,Process    = PID,g" \
	-e "s,^Generated.*= [0-9][0-9]*,Generated  = TIMESTAMP,g" \
	-e 's/interval = [0-9][0-9]*/interval = TIME/' \
	-e 's/eggs"] = [0-9][0-9]* (value=[0-9][0-9]*/eggs"] = N (value=N/' \
    #end
}

echo "=== dump labels and values ==="
_run_valgrind $PCP_PMDAS_DIR/mmv/mmvdump $PCP_TMP_DIR/mmv/labels3 \
	| _filter_mmvdump \
	| _filter_paths

_filter_pminfo()
{
    sed \
	-e "s/.domainname.:.${domainname}./\"domainname\":\"DOMAIN\"/g" \
	-e "s/.machineid.:.${machineid}./\"machineid\":\"MACHINE\"/g" \
	-e "s/.hostname.:.${hostname}./\"hostname\":\"HOSTNAME\"/g" \
	-e "s/.groupid.:.[0-9][0-9]*/\"groupid\":GID/g" \
	-e "s/.userid.:.[0-9][0-9]*/\"userid\":UID/g" \
    #end
}

echo "=== check labels and values ==="
pmda="$PCP_PMDAS_DIR/mmv/pmda_mmv,mmv_init"
_run_valgrind pminfo -L -Kclear -Kadd,70,$pmda -d mmv.labels3 -l -M -f \
	| _filter_pminfo \
	| _filter_paths

status=0
exit
