#
# Common shell routines for testing the OpenMetrics PMDA.
#
# Copyright (c) 2017,2019 Red Hat.
#

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

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

CONFIG_DIR=$PCP_PMDAS_DIR/openmetrics/config.d

_pmdaopenmetrics_check()
{
    [ -f $PCP_PMDAS_DIR/openmetrics/pmdaopenmetrics.python ] || return 1
    [ -f $here/openmetrics/openmetrics_endpoint.python ] || return 1
    return 0
}

_have_python266()
{
    v=`python -V 2>&1 | awk '{print $NF}'`
    [ "$v" = "2.6.6" ] && return 0
    return 1
}

_pmdaopenmetrics_remove()
{
    echo
    echo "=== remove openmetrics agent ==="
    cd $PCP_PMDAS_DIR/openmetrics
    $sudo ./Remove >$tmp.out 2>&1
    _filter_pmda_remove <$tmp.out
}

_pmdaopenmetrics_install()
{
    # start from known starting points
    cd $PCP_PMDAS_DIR/openmetrics
    $sudo ./Remove >/dev/null 2>&1
    _service pmcd stop 2>&1 | _filter_pcp_stop

    echo
    echo "=== openmetrics agent installation ==="
    $sudo ./Install </dev/null >$tmp.out 2>&1
    cat $tmp.out >>$here/$seq.full
}

_pmdaopenmetrics_save_config()
{
    $sudo rm -rf $CONFIG_DIR.$seq
    $sudo mv $CONFIG_DIR $CONFIG_DIR.$seq
    $sudo mkdir -p $CONFIG_DIR
    $sudo chmod 777 $CONFIG_DIR
    for f in $PCP_VAR_DIR/config/pmda/144.*.py; do
	[ -f "$f" ] && $sudo mv -f $f $f.$seq
    done
}

_pmdaopenmetrics_restore_config()
{
    $sudo rm -rf $CONFIG_DIR
    $sudo mv $CONFIG_DIR.$seq $CONFIG_DIR
    $sudo chmod 755 $CONFIG_DIR
    $sudo rm -f $PCP_VAR_DIR/config/pmda/144.*.py
    for f in $PCP_VAR_DIR/config/pmda/144.*.py.$seq; do
	[ -f "$f" ] && $sudo mv -f $f `echo $f | sed -e "s/\.$seq//"`
    done
}

# wait for the PMDA to dynamically create a named metric (or subtree)
_pmdaopenmetrics_wait_for_metric()
{
    metric="$1"
    configdir="$2"
    [ -z "$metric" ] && metric=openmetrics.control.calls
    [ -z "$configdir" ] && configdir=$CONFIG_DIR

    # wait for the requested metric to appear in the pmns
    _i=0
    while [ $_i -lt 30 ]
    do
    	if pminfo $metric >/dev/null 2>&1
	then
	    # all good
	    return 0
	fi
	sleep 1
	_i=`expr $_i + 1`
    done

    # timeout, fail
    echo _pmdaopenmetrics_wait_for_metric FAILED for metric $metric
    return 1
}
