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

set -euo pipefail
source es_util_env
source logging

function usage() {
cat << EOF

Exports a given user's kibana objects from their unique
kibana index and write the results to STDOUT as an Elasticsearch
search response.

usage:
  $0 <username> [objects]

  username   the user's name or '\$\$kibana' if it should retrieve
             the '.kibana' objects
  objects    a comma delimited list of objects (Defaults: visualization,dashboard,search)

EOF
exit 1
}

if [ -z "${1:-}" ] ; then
    usage
fi

username=$1
OBJECTS=${2:-visualization,dashboard,search}
CMD=${CMD:-es_util}
kibindex=$( get_kibana_index_name "${username}" )

if [ "$username" == '$$kibana' ] ; then
    kibindex=.kibana
fi

resp_code=$(${CMD} --query="$kibindex" \
                  --request HEAD --head --output /dev/null \
                  -w '%{response_code}' )

if [ "$resp_code" != 200 ] ; then
    error Could not find kibana index ${kibindex} for user ${username}: $resp_code
    exit 1
fi

${CMD} --query="${kibindex}/${OBJECTS}/_search?pretty"
