#!/usr/bin/env bash

# Run example:
# OPENSEARCH_ENDPOINT="https://opensearch.corp1.majordomo.ru" OPENSEARCH_PASSWORD="$(pass show majordomo/public/opensearch-dashboards/admin)" OPENSEARCH_QUERY_SIZE=5 OPENSEARCH_QUERY_NAMESPACE=opensearch OPENSEARCH_QUERY_MINUTES=5 /home/oleg/.local/share/chezmoi/dot_local/bin/executable_opensearch search

OPENSEARCH_ARGS=(
    --user "admin:${OPENSEARCH_PASSWORD}"
)

case "$1" in
    search)
        opensearch_query()
        {
            cat <<EOF
{
  "version": true,
  "size": ${OPENSEARCH_QUERY_SIZE:-1000},
  "sort": [
    {
      "@timestamp": {
        "order": "desc",
        "unmapped_type": "boolean"
      }
    }
  ],
  "aggs": {
    "2": {
      "date_histogram": {
        "field": "@timestamp",
        "calendar_interval": "1m",
        "time_zone": "Europe/Moscow",
        "min_doc_count": 1
      }
    }
  },
  "stored_fields": [
    "*"
  ],
  "script_fields": {},
  "docvalue_fields": [
    {
      "field": "@timestamp",
      "format": "date_time"
    },
    {
      "field": "time",
      "format": "date_time"
    }
  ],
  "_source": {
    "excludes": []
  },
  "query": {
    "bool": {
      "must": [],
      "filter": [
        {
          "match_all": {}
        },
        {
          "match_phrase": {
            "kubernetes.namespace_name.keyword": "${OPENSEARCH_QUERY_NAMESPACE}"
          }
        },
        {
          "range": {
            "@timestamp": {
              "gte": "$(date -u -d "-${OPENSEARCH_QUERY_MINUTES:-60} minutes" +"%Y-%m-%dT%H:%M:%S.%3NZ")",
              "lte": "$(date -u +"%Y-%m-%dT%H:%M:%S.%3NZ")",
              "format": "strict_date_optional_time"
            }
          }
        }
      ],
      "should": [],
      "must_not": []
    }
  },
  "highlight": {
    "pre_tags": [
      "@opensearch-dashboards-highlighted-field@"
    ],
    "post_tags": [
      "@/opensearch-dashboards-highlighted-field@"
    ],
    "fields": {
      "*": {}
    },
    "fragment_size": 2147483647
  }
}
EOF
        }
        echo "$(opensearch_query)" \
            | curl --max-time 5 \
                   --insecure \
                   --silent "${OPENSEARCH_ARGS[@]}" \
                   --header 'Content-Type: application/json' \
                   --data @- \
                   "${OPENSEARCH_ENDPOINT}/logstash-*/_search" \
            | jq --raw-output '.hits.hits | group_by(._source.kubernetes.pod_name)[][] | [._source.kubernetes.pod_name, ._source.log] | @tsv' \
            | sort --version-sort
        ;;
esac
