#!/bin/sh
# PCP QA Test No. 1976
# Test pmdaopenmetrics metric removal
#
# Copyright (c) 2017, 2025 Red Hat.  All Rights Reserved.
#
seq=`basename $0`
echo "QA output created by $seq"

# get standard environment, filters and checks
. ./common.openmetrics

_pmdaopenmetrics_check || _notrun "openmetrics pmda not installed"

status=1        # failure is the default!

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

_prepare_pmda openmetrics
trap "_cleanup; exit \$status" 0 1 2 3 15
_stop_auto_restart pmcd

_pmdaopenmetrics_save_config

# add all the sample text files as urls.
# need to be a place the user $PCP_USER (pmcd) can read
#
( cd $here/openmetrics/samples; ls -1 *.txt ) | sort | while read file
do
    cp $here/openmetrics/samples/$file $tmp.$file
    urlbase=`basename "$file" .txt | tr .- _`
    echo 'file://'$tmp.$file >$tmp.tmp
    $sudo cp $tmp.tmp $PCP_PMDAS_DIR/openmetrics/config.d/$urlbase.url
done
ls -l $PCP_PMDAS_DIR/openmetrics/config.d >>$seq_full

# add all the sample scripts
cp -a $here/openmetrics/scripts/* $PCP_PMDAS_DIR/openmetrics/config.d
find $PCP_PMDAS_DIR/openmetrics/config.d -name GNU\* -exec rm -f {} ";"

_pmdaopenmetrics_install

if ! _pmdaopenmetrics_wait_for_metric openmetrics.thermostat
then
    status=1
    exit
fi

echo "-- metric removal of new source/metric --"
$sudo rm $PCP_PMDAS_DIR/openmetrics/config.d/simple_metric.url
pminfo openmetrics.simple_metric
echo

echo "-- source re-addition --"
# same access controls logic as above, user $PCP_USER needs to be
# able to read the file at the end of the URL
#
cp $here/openmetrics/samples/simple_metric.txt $tmp.simple_metric.txt
echo 'file:///'$tmp.simple_metric.txt >$PCP_PMDAS_DIR/openmetrics/config.d/simple_metric.url
pminfo openmetrics.simple_metric
echo

echo "-- metric removal of recognized source/metric --"
$sudo rm $PCP_PMDAS_DIR/openmetrics/config.d/simple_metric.url
pminfo openmetrics.simple_metric
echo

echo "-- source re-addition with epoch timestamp --"
cp $here/openmetrics/samples/simple_metric.txt $tmp.simple_metric.txt
echo 'file:///'$tmp.simple_metric.txt > $PCP_PMDAS_DIR/openmetrics/config.d/simple_metric.url
$sudo touch -t 197001010000 $PCP_PMDAS_DIR/openmetrics/config.d/simple_metric.url
pminfo openmetrics.simple_metric
echo

_pmdaopenmetrics_remove >/dev/null 2>&1

# success, all done
status=0
exit
