#!/bin/bash

cd ~/Desktop/Work4all-system/

customer_number=$(jq '.general.customer_number' config.json)
apikey=$(jq -r '.general.apikey' config.json) # -r flag is for "raw" to remove double quotes from string values before storing it as a var
url=$(jq -r '.general.update_url' config.json) # -r flag is for "raw" to remove double quotes from string values before storing it as a var
mssql=$(jq '.containers.mssql.enabled' config.json)

container_names="backend frontend traefik"

if [ $mssql = true ]; then
    container_names="$container_names mssql"
fi

json_output="{ \"number\" : \"$customer_number\", \"apikey\" : \"$apikey\", \"metrics\" : {"

for container_name in $container_names; do
    stats=$(docker stats "$container_name" --no-stream --format "{{.CPUPerc}}:{{.MemUsage}}" | awk -F/ '{print $1}')

    cpu_percentage=$(echo "$stats" | cut -d ':' -f1)
    memory_usage=$(echo "$stats" | cut -d ':' -f2)

    json_output+=" \"$container_name\" : { \"cpu\" : \"$cpu_percentage\", \"memory\" : \"$memory_usage\" }, "
done

# Removing the trailing comma and closing the JSON string
json_output="${json_output%, *} } }"

echo "$json_output"


api_endpoint="https://api.$url/health_checks"
curl -k -X POST -H "Content-Type: application/json" -d "$json_output" "$api_endpoint"