#!/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_redis_server_version_offline

_cleanup()
{
    [ -n "$port" ] && redis-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 Redis server ==="
redisport=`_find_free_port`
redispath=`_find_redis_modules`
redisearch="$redispath/redisearch.$DSO_SUFFIX"
# workaround until https://bugs.debian.org/cgi-bin/bugreport.cgi?bug=989385 is fixed
sudo chmod +x $redisearch
# RediSearch module is only accessible by the redis user
sudo -u redis redis-server --port $redisport --save "" --loadmodule $redisearch > $tmp.redis 2>&1 &
echo "PING"
pmsleep 0.125
port="-p $redisport"
redis-cli $port ping
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 that Redisearch indexes records asynchronously and therefore they may be 
    # delay before "score" "stabilizes" until all records are process - this may take longer then adding of records itself
    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.redis >> $seq.full

# success, all done
status=0
exit
