#!/bin/sh
# PCP QA Test No. 2100
# Verify pmproxy -Q and -S authentication flags are accepted
# and that -S (reqauth) enforces authentication on REST API
#
# Copyright (c) 2026 Red Hat.  All Rights Reserved.
#

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

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

which curl >/dev/null 2>&1 || _notrun "no curl executable installed"

_cleanup()
{
    [ -n "$__pid" ] && $PCP_BINADM_DIR/pmsignal $__pid >/dev/null 2>&1
    cd $here
    $sudo rm -rf $tmp $tmp.*
}

status=0	# success is the default!
__pid=""
trap "_cleanup; exit \$status" 0 1 2 3 15

# real QA test starts here

echo "=== checking -Q and -S appear in usage ==="
pmproxy --help 2>&1 | grep -E '\-[QS]' | sed -e 's/^  *//'

echo
echo "=== checking -S enforces authentication on REST API ==="
__port=`_find_free_port`
$PCP_BINADM_DIR/pmproxy -S -f -p $__port -l $tmp.log &
__pid=$!
_wait_for_pmproxy $__port $tmp.log || _exit 1

echo "pmproxy with -S started"

# unauthenticated request should be rejected
__code=`curl -s -o /dev/null -w '%{http_code}' "http://localhost:$__port/pmapi/context?hostspec=localhost" 2>/dev/null`
if [ "$__code" = "403" ]; then
    echo "unauthenticated request correctly rejected (HTTP $__code)"
else
    echo "FAIL: expected HTTP 403, got HTTP $__code"
fi

$PCP_BINADM_DIR/pmsignal $__pid >/dev/null 2>&1
wait $__pid 2>/dev/null
__pid=""

echo
echo "=== checking without -S allows unauthenticated access ==="
__port=`_find_free_port`
$PCP_BINADM_DIR/pmproxy -f -p $__port -l $tmp.log2 &
__pid=$!
_wait_for_pmproxy $__port $tmp.log || _exit 1

echo "pmproxy without -S started"

# unauthenticated request should succeed
__code=`curl -s -o /dev/null -w '%{http_code}' "http://localhost:$__port/pmapi/context?hostspec=localhost" 2>/dev/null`
if [ "$__code" = "200" ]; then
    echo "unauthenticated request correctly allowed (HTTP $__code)"
else
    echo "FAIL: expected HTTP 200, got HTTP $__code"
fi

$PCP_BINADM_DIR/pmsignal $__pid >/dev/null 2>&1
wait $__pid 2>/dev/null
__pid=""

# success, all done
exit
