#!/bin/bash -e
#
# Copyright 2017 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.
set -euo pipefail

if [ -z "${OC_CMD:-}" ] ; then
  source es_util_env
fi

shard=${SHARD:-0}

helpMsg() {
cat <<MSG

 Usage: $0 <index> [es_node] [options]
 Command to manually allocate a replica shard
   Ref: https://www.elastic.co/guide/en/elasticsearch/reference/5.6/cluster-reroute.html

   args:
     index                Required. The index to allocate(e.g. .kibana.02c55f18a892b365bcd1802db9e5c9df39c04674)
     es_node              Optional. The name of the Elasticsearch node (Default: ${DC_NAME:-})

   options:
     --shard=<number>            The shard to allocate. (Default: ${shard})
     --help,-h                   This message.
MSG
}

index=${1:-}
node="${2:-${DC_NAME:-}}"

if [ -z "${index}" ]; then
    helpMsg
    exit 1
fi

while (($#))
do
case $1 in
    --shard=*)
      shard=${1#*=}
      ;;
    --help|-h)
      helpMsg
      exit 0
      ;;
  esac
  shift
done

payload="{\"commands\":[{\"allocate_replica\":{\"index\":\"${index}\",\"shard\":${shard},\"node\":\"${node}\"}}]}"

${OC_CMD:-} es_util --query=_cluster/reroute?pretty -XPOST -d ${payload}

