#!/bin/bash -e
#
# 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.

source "logging"

info Adding index templates
shopt -s failglob
for template_file in ${ES_HOME}/index_templates/*.json
do
    if [ -f ${template_file}.bkup ]; then
      rm ${template_file}
      mv ${template_file}.bkup ${template_file}
    fi

    sed -i.bkup "s,\$REPLICA_SHARDS,$REPLICA_SHARDS," $template_file
    sed -i "s,\$PRIMARY_SHARDS,$PRIMARY_SHARDS," $template_file
    template=`basename $template_file`
    # Check if index template already exists
    response_code=$(es_util --query=_template/$template \
        ${DEBUG:+-v} -s \
        --request HEAD --head --output /dev/null \
        -w '%{response_code}')
    if [ "${response_code}" == "200" ]; then
        info "Index template '$template' found in the cluster, overriding it"
    else
        info "Create index template '$template'"
    fi
    es_util --query=_template/$template \
        ${DEBUG:+-v} -s -X PUT \
        -d@${template_file}

done
shopt -u failglob
info Finished adding index templates
