#!/bin/bash

# Collect running container IDs
container_ids=$(docker ps -q)

# Start JSON array
echo "["

first=true

for cid in $container_ids; do
    # Get basic info
    name=$(docker inspect --format '{{.Name}}' "$cid" | sed 's/^\/\(.*\)/\1/')
    image=$(docker inspect --format '{{.Config.Image}}' "$cid")
    container_id=$(docker inspect --format '{{.Id}}' "$cid")

    # RAM usage in bytes (from docker stats)
    mem_usage=$(docker stats --no-stream --format "{{.MemUsage}}" "$cid")
    # mem_usage looks like "12.34MiB / 1.944GiB" — extract the used part
    mem_used=$(echo "$mem_usage" | awk '{print $1}')

    # Convert mem_used to MiB as a number
    # Support KiB, MiB, GiB units
    ram_usage=$(echo "$mem_used" | awk '
    {
        val = substr($0, 1, length($0)-3)
        unit = substr($0, length($0)-2, 3)
        if (unit == "KiB") print val / 1024
        else if (unit == "MiB") print val
        else if (unit == "GiB") print val * 1024
        else print 0
    }')

    # Traefik labels (extract labels JSON)
    labels=$(docker inspect --format '{{json .Config.Labels}}' "$cid" | jq -r 'to_entries | map(select(.key | test("^traefik.*"))) | map({(.key): .value}) | add')

    # Comma between JSON objects
    if [ "$first" = false ]; then
        echo ","
    fi
    first=false

    # Output JSON object
    jq -n \
        --arg name "$name" \
        --arg id "$container_id" \
        --arg image "$image" \
        --argjson ram "$ram_usage" \
        --argjson tags "$labels" \
        '{
            name: $name,
            id: $id,
            image: $image,
            ram_mb: $ram,
            traefik_tags: $tags
        }'
done

# End JSON array
echo "]"

