#!/bin/bash

# test init script tests cleanup of kibana index patterns
# that have $TITLE$ in the title field that
# https://bugzilla.redhat.com/show_bug.cgi?id=1656086
LOGGING_NS=${LOGGING_NS:-openshift-logging}

if [ -n "${DEBUG:-}" ] ; then
    set -x
fi

source "$(dirname "${BASH_SOURCE[0]}" )/../hack/lib/init.sh"
source "${OS_O_A_L_DIR}/hack/testing/util.sh"
os::util::environment::use_sudo

test_name=$(basename $0)
init_script="0510-bz1656086-remove-index-patterns-with-bad-title"
os::test::junit::declare_suite_start ${test_name}

cleanup() {
    local return_code="$?"
    set +e
    if [ $return_code = 0 ] ; then
        mycmd=os::log::info
    else
        mycmd=os::log::error
    fi
    $mycmd ${test_name} test finished at $( date )
    # this will call declare_test_end, suite_end, etc.
    os::test::junit::reconcile_output
    exit $return_code
}
trap "cleanup" EXIT

seed_kibana_data(){
  local pod=$1
  local title=$2
  os::log::info Seeding 20 Kibana index-patterns with title: "${title}"
  names=(abc123 xyz123 gef123 kjl123 zzz123)
  for n in "${names[@]}"
  do
    for i in $(seq 1 4)
    do
      title=${title:-"project.foo${i}.${n}.*"}
      doc=".kibana.$n/index-pattern/project.foo${RANDOM}.${n}.*"
      result=$(oc -n ${LOGGING_NS} exec -c elasticsearch $pod -- es_util --query=$doc -XPOST -d "{\"title\":\"$title\"}")
      if [ $? -ne 0 ] ; then
        os::log::error Error seeding index-patterns
        exit 1
      fi
    done
  done
}

function get_total_hits() {
echo $1 | python -c  "
import json
import sys
resp = json.load(sys.stdin)
print resp['hits']['total']
"
}

os::log::info Starting ${test_name} test at $( date )

espod=$( get_es_pod es )
cmd="oc exec -c elasticsearch -n ${LOGGING_NS} $espod"

# remove kibana indices
os::cmd::expect_success "$cmd -- es_util --query=.kibana* -XDELETE"

# verify 0 index-patterns is a no-op and script succeeds
os::log::info 'Verify init script with no kibana indices where title=$TITLE$'
os::cmd::expect_success "$cmd -- /usr/share/elasticsearch/init/$init_script"

# verify index-patterns are removed
os::log::info "Verify init script with some kibana indices"
#reset and seed good and bad data
os::cmd::expect_success "$cmd -- es_util --query=.kibana* -XDELETE"
seed_kibana_data $espod "sometitle"
seed_kibana_data $espod '$TITLE$'
sleep 3

os::cmd::expect_success "$cmd -- /usr/share/elasticsearch/init/$init_script"
sleep 5
remaining=$($cmd -- es_util --query='.kibana*/index-pattern/_count?q=title:$TITLE$' | python -c 'import json,sys;obj=json.load(sys.stdin);print obj["count"]')

if [ $remaining -ne 0 ] ; then
    os::log::error Found $remaining index-patterns in response that had 'title' equal to '$TITLE$'
    $cmd -- es_util --query='.kibana*/index-pattern/_search?pretty&_source=false&q=title:$TITLE$' 2>&1 | artifact_out
    exit 1
fi
