#!/bin/bash
set -e
#set -x
#trap read DEBUG
[[ -z $1 ]] && echo "Usage: prepare_plan.sh loadtest20190101.yaml" && exit -2
[[ -d $1 ]] && CFG="$1.yaml" || CFG=$1
[[ -f $1 ]] && WC=$(echo $1 | sed 's:.yaml::') || WC=$1

source static/helpers.sh

get_plan() {
    #set -e
    #trap read DEBUG
    j=(${INSTANCE//:/ })
    FN=$(echo $1 | sed 's:%IPORT%:'"${j[1]}"':')
    ssh ${j[0]} "EVLOGDUMP=\$(ls -1t /place/db/iss3/instances/*/evlogdump | head -1); PORT=${j[1]}; set -x;"`
               `"\$EVLOGDUMP /db/www/logs/$FN -i ContextCreated -s \$((\$(date +%s)-$2))000000 | "`
               `"awk '(\$2 * 997) % 100 < $PERC' |"`
               `"awk '{print \$1 \" %IPORT% GET /yandsearch?\" \$4 \"&hinternal=1&internal=1 HTTP/1.1\";}\' | "`
               `"sed -e 's:/yandsearch?&:/yandsearch?:' | head -n 20000 | "`
               `"pv -fbpet -i 5 -s 250m | gzip -c > tmp_plan.txt.gz; echo Dump completed"
    scp ${j[0]}:tmp_plan.txt.gz ./
    [[ $(gunzip -c tmp_plan.txt.gz | wc -l) -gt 5000 ]] && return 0
 
    echo "Too few queries fetched, retrying..."
    ssh ${j[0]} "rm tmp_plan.txt.gz"
    return -1
}

SERVICE=$(fgrep plan_mmeta_source $CFG | cut -f2 -d:)
PERC=$(fgrep plan_mmeta_percent $CFG | cut -f2 -d:); [[ -z $PERC ]] && PERC="5"

CONF=$(get_blinov_for_service $SERVICE)
echo "Getting plain queries from service $CONF"
INSTANCE=$(sky listinstances --no_tag "$CONF" | sort -r | head -1)
echo "Will obtain ${PERC}% realistic plan from $INSTANCE:"
J=(${INSTANCE//:/ })

cd $WC
get_plan current-eventlog-mmeta-%IPORT% 1800 || \
    get_plan eventlog-mmeta-%IPORT%.PREV 3600 || \
    get_plan current-eventlog-mmeta-%IPORT% 10800 || \
    get_plan eventlog-mmeta-%IPORT%.PREV 43200 || \
    { echo "Failed to get plan"; [[ "" ]]; }

mv tmp_plan.txt.gz plan.txt.gz

echo "Fetched plan with $(gunzip -c plan.txt.gz | wc -l) requests - OK"
