#!/bin/bash

BASEPATH="$(dirname "$0")"
source "$BASEPATH/volume-utils.sh"
static_file_list="$BASEPATH/static-file-path-list.txt"

# Read the JSON input and extract the list of keys
keys=$(get_persistent_volume_keys "/root/rpc/$1.yml")

static_size=0
total_size=0

# Iterate over the list of keys
for key in $keys; do
    #echo "checking: /var/lib/docker/volumes/rpc_$key"

    prefix="/var/lib/docker/volumes/rpc_$key"

    volume_size=$(du -sL $prefix 2>/dev/null | awk '{print $1}')

    total_size=$((total_size + volume_size))

    # Only check static files if the list exists
    if [[ -f "$static_file_list" ]]; then
        while IFS= read -r path; do
            # Skip empty lines
            [[ -z "$path" ]] && continue
            
            # Match rule: an entry with NO slash is root-level only (depth-1 under _data), so
            # e.g. `snapshots` won't catch postgres pg_logical/snapshots. An entry WITH a slash
            # is a path-suffix (any prefix: network-prefixed nitro, nested l2geth geth/geth/...).
            # Match real dirs AND symlinks: an OFFLOADED static dir is a symlink to /slowdisk,
            # which `find -type d` alone would skip.
            matches=()
            if [[ "$path" == */* ]]; then
                while IFS= read -r d; do matches+=("$d"); done < <(find "$prefix/_data" \( -type d -o -type l \) -path "*/$path" 2>/dev/null)
            else
                m="$prefix/_data/$path"; { [ -d "$m" ] || [ -L "$m" ]; } && matches+=("$m")
            fi
            for m in "${matches[@]}"; do
                size=$(du -sL "$m" 2>/dev/null | awk '{print $1}')
                static_size=$((static_size + ${size:-0}))
                size_formatted=$(echo "$(( ${size:-0} * 1024 ))" | numfmt --to=iec --suffix=B --format="%.2f")
                # offload indicator: is this static dir symlinked out to the /slowdisk extra disk?
                if [ -L "$m" ]; then
                    tgt=$(readlink -f "$m" 2>/dev/null)
                    case "$tgt" in
                        /slowdisk/*) loc="[OFFLOADED -> $tgt]" ;;
                        "")          loc="[BROKEN SYMLINK -> $(readlink "$m" 2>/dev/null)]" ;;
                        *)           loc="[SYMLINK -> $tgt]" ;;
                    esac
                else
                    loc="[on-disk]"
                fi
                echo "$size_formatted  $m  $loc" >&2
            done
        done < "$static_file_list"
    fi
done

# Calculate ratio, handling division by zero
if [[ $total_size -eq 0 ]]; then
    ratio="0.00"
else
    ratio=$(bc -l <<< "scale=2; $static_size/$total_size")
fi

echo "$ratio"
