#!/bin/bash

# test init script tests cleanup of old SG indices
# https://bugzilla.redhat.com/show_bug.cgi?id=1658632
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"
source "${OS_O_A_L_DIR}/elasticsearch/init/common"

os::util::environment::use_sudo

test_name=$(basename $0)
init_script="0530-bz1667801-fix-kibana-replica-shards"
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_data(){
  os::log::info Seeding data for the test
  local pod=$1
  names=(abc123 xyz123 zzz123)
  for n in "${names[@]}"
  do
    index=".kibana.$n"
    os::log::info Creating index $index
    result=$(oc -n ${LOGGING_NS} exec -c elasticsearch $pod -- es_util --query=$index -XPUT -d '{"settings": {"index":{"number_of_replicas":"2"}}}')
    if echo $result | grep -q error ; then
      os::log::error Error seeding indices: $result
      exit 1
    fi
  done
}

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

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

# remove existing indices
os::log::info Remove existing kibana indices
os::cmd::expect_success "$cmd -- es_util --query=.kibana.* -XDELETE"
sleep 1

# verify no matches indices is a no-op and script succeeds
os::log::info 'Verify init script with no matching indices'
os::cmd::expect_success "$cmd -- /usr/share/elasticsearch/init/$init_script"

# verify indices are removed
os::log::info "Verify init script with some kibana indices"
seed_data $espod
sleep 3
script='REPLICA_SHARDS=1'
script="$script /usr/share/elasticsearch/init/$init_script"
os::cmd::expect_success "$cmd -- bash -c '$script'"
sleep 3

#verify indices updated
count=$($cmd -- es_util --query='.kibana.*/_settings/index.number_of_replicas?pretty' | grep '"number_of_replicas" : "1"' | wc -l)
if [ $count -ne 3 ] ; then
    os::log::error Kibana indices with number_of_replicas:1 should be 3 but is $count
    $cmd -- es_util --query='.kibana*/_settings/index.number_of_replicas?pretty' 2>&1 | artifact_out
    exit 1
fi
