#!/bin/sh
# PCP QA Test No. 1871
# Exercise pmsearch functionality.
#
# Copyright (c) 2020 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

_check_series
_check_search
_check_key_server_version_offline

_cleanup()
{
    [ -n "$port" ] && $keys_cli $port shutdown
    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

# real QA test starts here
echo "=== Start test key server ==="
key_server_port=`_find_free_port`
key_server_name=`_find_key_server_name`
key_server_path=`_find_key_server_modules`
key_server_search=`_find_key_server_search`
keysearch="$key_server_path/$key_server_search.$DSO_SUFFIX"
# workaround until https://bugs.debian.org/cgi-bin/bugreport.cgi?bug=989385 is fixed
sudo chmod +x $keysearch
# module is only accessible by the associated key server user account
sudo -u $key_server_name $key_server --port $key_server_port --save "" --loadmodule $keysearch > $tmp.keys 2>&1 &
port="-p $key_server_port"
_check_key_server_ping $key_server_port
echo

echo "=== Load an empty index ==="
pmsearch $port no results

echo "=== Load deterministic search content ==="
_filter_load()
{
    sed \
	-e "s,$here,PATH,g" \
    #end
}
pmseries $port --load $here/archives/sample-labels | _filter_load

search_terms="99 random interesting result"
for term in $search_terms
do
    echo "=== Search on $term ==="
    pmsearch $port -C $term
done

echo "=== Search engine info ==="
_filter_info()
{
    sed \
	-e 's/: [0-9][0-9]*\.[0-9][0-9]*/: DOUBLE/g' \
	-e 's/: [0-9][0-9]*/: INTEGER/g' \
    #end
}
pmsearch $port -i -C | _filter_info

echo "=== Extra reporting - timing, score, hits, doc IDs ==="
_filter_extras()
{
    # need to filter out score, since it seems the search module indexes
    # records asynchronously and therefore there may be a delay before
    # "score" "stabilizes" until all records are processed - this may
    # take longer then the adding of the records themselves
    sed \
	-e 's/\(Score:\) 0\.[0-9][0-9]*/\1 0.XX/g' \
	-e 's/\([0-9][0-9]* hit in\) 0\.[0-9][0-9]* seconds/\1 0.X seconds/g' \
	-e 's/\([0-9][0-9]* hits in\) 0\.[0-9][0-9]* seconds/\1 0.Y seconds/g' \
    #end
}
pmsearch $port -dStT 99 | _filter_extras

echo "=== Suggestion search 1 ==="
pmsearch $port -s sample | _filter_extras

echo "=== Suggestion search 2 ==="
pmsearch $port -s blue | _filter_extras

echo "=== Indom search ==="
pmsearch $port -n 29.3 | _filter_extras


cat $tmp.keys >> $seq.full

# success, all done
status=0
exit
