#!/usr/bin/env bash
set -euo pipefail
ztail_file=$(mktemp /tmp/ztail-logs.XXXXXX)
scriptstring="
import sys, json;
deploy=json.load(sys.stdin)['hits']['hits'];
try:
    for doc in deploy:
        sys.stdout.write('{}    {}\n'.format(doc['_source']['timestamp'],
                                             doc['_source']['msg'].rstrip()))
except IOError:
    pass
"

body='{
  "size": 10000,
  "query": {
    "bool": {
      "must": [
        {"match_phrase":{"deploy_id": "passed_id"}}
      ],
      "filter": [
        { "range": { "log_line": { "lte": "upper_limit", "gte": "lower_limit" }}}
      ]
    }
  },
  "sort":{"log_line": "asc"}}
}'
es_url='https://search-metrics-production-c65mdhdibmbmkl4pfiqsj5yhmq.us-west-2.es.amazonaws.com/ztail*/_search'

create_log () {
    while true; do
        lower_limit="$(cat $ztail_file | wc --lines)"
        upper_limit="$(( lower_limit + 2000 ))"
        command="${body/"passed_id"/$1}"
        command="${command/"upper_limit"/$upper_limit}"
        command="${command/"lower_limit"/$lower_limit}"
        curl --silent --header "Content-Type:application/json" \
        --request GET --data "$command" \
        $es_url | python3 -c "$scriptstring" >> $ztail_file
        sleep 2
    done
}

if [ $# -eq 0 ]
    then
    echo "NEED TO PASS DEPLOYMENT_ID AS AN ARGUMENT"
    echo "Usage: ./ztail <deployment_id>"
else
    create_log $1 &
    tail --follow $ztail_file
fi
