#!/bin/bash -e

source "logging"

set -euo pipefail

if [ -n "${DEBUG:-}" -o $loglevelint = 7 ] ; then
    set -x
    curl_output() {
        python -mjson.tool
    }
else
    curl_output() {
        cat > /dev/null 2>&1
    }
fi

usage() {
    error Usage: $0 user-name
    error The kibana index for the given user must already exist
    error And assumes Elasticsearch is configured to have a unique
    error Kibana index for each user.
}

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

kibindex=$( get_kibana_index_name "$1" )

resp_code=$( es_util --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 $1: $resp_code
    exit 1
fi

info Adding Kibana dashboards and other UI objects for user $1 index $kibindex

INDEX_PATTERN=${INDEX_PATTERN:-project.*}
INDEX_PATTERN_FILE=${INDEX_PATTERN_FILE:-$ES_HOME/index_patterns/com.redhat.viaq-openshift.index-pattern.json}
INDEX_PATTERN_TYPE=${INDEX_PATTERN_TYPE:-index-pattern}
KIBANA_UI_OBJECTS_DIR=${KIBANA_UI_OBJECTS_DIR:-$ES_HOME/kibana_ui_objects}

info Adding the index pattern for "$INDEX_PATTERN" . . .

cat $INDEX_PATTERN_FILE | \
    sed "s/[$]TITLE[$]/$INDEX_PATTERN/g" | \
    es_util --query="$kibindex/$INDEX_PATTERN_TYPE/$INDEX_PATTERN" -XPUT --data-binary @- | curl_output

info Adding the Kibana UI objects . . .
{
    for file in $KIBANA_UI_OBJECTS_DIR/*.json ; do
        if [ ! -f "$file" ] ; then
            error Missing file "$file" in $KIBANA_UI_OBJECTS_DIR
            ls -alrtF $KIBANA_UI_OBJECTS_DIR
            continue
        fi
        cat "$file" | python -c '
import sys
import json
obj = json.load(sys.stdin)
for doc in obj:
  hdr = {"create":{"_type":doc["_type"],"_id":doc["_id"]}}
  json.dump(hdr, sys.stdout)
  sys.stdout.write("\n")
  json.dump(doc["_source"], sys.stdout)
  sys.stdout.write("\n")
'
    done
} | es_util --query="$kibindex/_bulk" -H "Content-type: application/json" -XPOST --data-binary @- | curl_output

info Success
