#!/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.
#
# Utility to grab documents from the ES
# instance using the admin certs and keys
set -euo pipefail
source es_util_env

while (($#))
do
case $1 in
    --query=*)
      QUERY=${1#*=}
      ;;
    *)
      break;
      ;;
  esac
  shift
done

QUERY=${QUERY:-""}
INDEX=${INDEX:-"project.*"}
TYPE=${TYPE:-"_search"}
SIZE=${SIZE:-10}
SORT=${SORT:-"@timestamp:desc"}
OPTIONS=${OPTIONS:-"size=$SIZE&sort=$SORT&pretty"}
# so if you want to use es_util with no content type, call it like this:
# CONTENT_TYPE= .. es_util --query=...
# to use your own custom content type, you can either set
# CONTENT_TYPE="application/ndjson" .. es_util --query="" -X POST ...
# or provide your own headers
# CONTENT_TYPE= .. es_util --query="" -X POST -H "Content-type:application/ndjson" ...
# by default we use Content-type:application/json because ES6 requires it for most
# of the sorts of es util commands we use
if [ -z "${CONTENT_TYPE+set}" ] ; then
    CONTENT_TYPE="application/json"
fi

ES_BASE=${ES_BASE:-https://localhost:9200}

if [ -z "${QUERY:-}" ]; then
  QUERY="$INDEX/$TYPE?$OPTIONS"
fi

curl -s -k --cert ${ES_PATH_CONF}/secret/admin-cert --key ${ES_PATH_CONF}/secret/admin-key \
     ${CONTENT_TYPE:+"-H"} ${CONTENT_TYPE:+"Content-type:"}${CONTENT_TYPE:-} \
     "$ES_BASE/$QUERY" "$@"
