#!/bin/bash

sfc="fms-sfc"
sfci="fms-sfc-1"
service_function="fms-storage"
endpoint="fms-storage-endpoint"
measurement="graph_measurement"
response_time_field="mean(processing_time_rate)/1000"
request_size_field="mean(bytes_received_rate)"
response_size_field="mean(bytes_sent_rate)"
ue="ue22"
rtt_measurement="graph_query"
query_period=30


while true
do
    echo "Building temporal graph..."

    end=$(date +%s)
    start=$((${end}-${query_period}))

    echo "Start - ${start}, End - ${end}"
    JSON_STRING=$( jq -n \
                  --arg sfc "${sfc}" \
                  --arg sfci "${sfci}" \
                  --arg sf "${service_function}" \
                  --arg measurement "${measurement}"\
                  --arg response_time "${response_time_field}"\
                  --arg request_size "${request_size_field}"\
                  --arg response_size "${response_size_field}"\
                  --argjson from ${start}\
                  --argjson to ${end}\
                  '{from: $from, to: $to, service_function_chain: $sfc, service_function_chain_instance: $sfci, service_functions: {($sf): {measurement_name: $measurement, response_time_field: $response_time, request_size_field: $request_size, response_size_field: $response_size}}}' )
    echo ${JSON_STRING}
    echo "Sending build request to CLMC"
    response=$(curl -s -X POST -d "${JSON_STRING}" http://172.40.231.51/clmc-service/graph/temporal)
    echo ${response}
    timestamp=$(echo ${response} | jq -r '.graph.time_range.to')
    graph_uuid=$(echo ${response} | jq -r '.graph.uuid')
    echo ${graph_uuid}
    echo ${timestamp}

    echo "Querying for round-trip time..."
    response=$(curl -s -X GET "http://172.40.231.51/clmc-service/graph/temporal/${graph_uuid}/round-trip-time?startpoint=${ue}&endpoint=${endpoint}")
    echo ${response}
    tags=$(echo ${response} | jq -r '.global_tags | to_entries | map("\(.key)=\(.value|tostring)") | join(",")')
    echo ${tags}
    rtt=$(echo ${response} | jq -r '.round_trip_time')
    echo ${rtt}

    measurement_line="${rtt_measurement},${tags} round_trip_time=${rtt} ${timestamp}"
    response=$(curl -si -XPOST "http://172.40.231.51/influxdb/write?db=${sfc}" --data-binary "${measurement_line}")
    echo ${response}

    echo "Deleting temporal graph..."
    echo $(curl -s -X DELETE "http://172.40.231.51/clmc-service/graph/temporal/${graph_uuid}")

    sleep ${query_period}

done