#!/bin/bash
#
# Copyright 2018 Red Hat, Inc. and/or its affiliates
# and other contributors as indicated by the @author tags.
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#    http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

# init script to cleanup kibana index patterns
# that have $TITLE$ in the title field to resolve:
# https://bugzilla.redhat.com/show_bug.cgi?id=1656086
set -e

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

source "logging"

script=$(basename $0)

info "Starting init script: ${script}"

function get_count(){
  echo $1 | python -c  '
import json
import sys
try:
  resp = json.load(sys.stdin)
  print resp["count"]
except:
  print 0
'
}

function get_deleted(){
  echo $1 | python -c  '
import json
import sys
try:
  resp = json.load(sys.stdin)
  print resp["deleted"]
except:
  print 0
'
}

response=$(es_util --query='.kibana*/index-pattern/_count?q=title:$TITLE$')
debug "Initial response:  $response"

tot_docs=$(get_count "$response")
info "Found ${tot_docs} index-patterns to remove"

response=$(es_util --query='.kibana*/index-pattern/_delete_by_query' -d '{"query":{"match":{"title":"$TITLE$"}}}')
if [ $(get_deleted $response) -ne ${tot_docs} ] ; then
  error "Error deleting index-patterns: $response"
fi

info "Completed init script: ${script}"
