#!/bin/bash

# This script updates default time range of dashboards before booting grafana-server. It:
# 1. probe prometheus until it works
# 2. use proper dashboard provisioning base on
# 3. get [start, end] time range by querying prometheus
# 4. set time range to dashboards
# 5. call official start script to boot grafana

set -ex

PROM_URL='http://prometheus-peer:9090'

# init_dashboard choose proper dashboard provisioning base on cluster type (k8s | tiup)
init_dashboard() {
    if [[ $CLUSTER_TYPE == "tiup" ]]; then
        mv /tiup-dashboards /dashboards
    else
        mv /k8s-dashboards /dashboards
    fi
}

# update_dashboard
update_dashboard() {
    # set grafana dashboard default time range: https://github.com/grafana/grafana/issues/2786#issuecomment-719779246
    start="$(_get_start_time)"
    end="$(_get_end_time)"

    for filename in /dashboards/*.json; do
        contents=`jq --arg ts "${start}" '.time.from = $ts' $filename` && \
        echo "${contents}" > $filename

        contents=`jq --arg ts "${end}" '.time.to = $ts' $filename` && \
        echo "${contents}" > $filename
    done
}

_get_start_time() {
    # get oldest timestamp, see: https://github.com/prometheus-junkyard/tsdb/pull/363
    start_ts=$(_get_timestamp "${PROM_URL}/api/v1/query?query=prometheus_tsdb_lowest_timestamp")
    start_ts=$((start_ts/1000))

    echo `TZ=Asia/Shanghai date -d @$start_ts -Iseconds`
}

_get_end_time() {
    # get latest timestamp of "pd_regions_status" since 90 days ago(naive way to get end timestamp)
    end_ts=$(_get_timestamp "${PROM_URL}/api/v1/query?query=max_over_time(timestamp(pd_regions_status)[90d:])")
    if [[ "$end_ts" =~ ^[+-]?[0-9]+$ ]]; then # integer in milliseconds
        end_ts=$((end_ts/1000))
    elif [[ $end_ts =~ ^[+-]?[0-9]*\.[0-9]+$ ]]; then # float point in seconds
        end_ts=${end_ts%.*}
    fi

    echo `TZ=Asia/Shanghai date -d @$end_ts -Iseconds`
}

_get_timestamp() {
    PROM_QUERY=$1

    INT_PATTERN="^[+-]?[0-9]+$"
    FLOAT_PATTERN="^[+-]?[0-9]*\.[0-9]+$"

    ts=`curl -s -g "$PROM_QUERY" | jq -r '.data.result[0].value[1]'`
    while [[ ! "$ts" =~ $INT_PATTERN && ! "$ts" =~ $FLOAT_PATTERN ]]; do # keep querying until ts is a valid number
        sleep 3
        ts=`curl -s -g "$PROM_QUERY" | jq -r '.data.result[0].value[1]'`
    done

    echo $ts
}

main() {
    init_dashboard
    update_dashboard
    /run.sh
}

main