#!/bin/bash
#
# Copyright 2019 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 indicies to have
# N replicas as defined by REPLICA_SHARD to resolve:
# https://bugzilla.redhat.com/show_bug.cgi?id=1667801
set -eu

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

source "logging"

script=$(basename $0)

info "Starting init script: ${script}"
replicas=${REPLICA_SHARDS:-0}

tot_indices=$(es_util --query=".kibana*/_settings/index.number_of_replicas?pretty" | grep number_of_replicas | grep -v "\"number_of_replicas\" : \"$replicas\"" | wc -l)
info "Found ${tot_indices} Kibana indices with replica count not equal to $replicas"

if [ $tot_indices -ne 0 ] ; then
  info "Updating all Kibana indices settings to have replica count: $replicas"
  response=$(es_util --query='.kibana*/_settings?pretty' -XPUT -d "{\"index\":{\"number_of_replicas\":$replicas}}")
  if [ $? -ne 0 ] ; then
    error "Error updating the Kibana indices replica count: $response"
  fi
fi

info "Completed init script: ${script}"
