#!/bin/bash

MODEL_PATH=${1:-/home/vraptor/comfyui/workspace/models/}

# 사이즈 변환 함수
human_readable() {
    local bytes=$1
    local units=("B" "KB" "MB" "GB" "TB")
    local unit=0

    while [ "$bytes" -gt 1024 ] && [ $unit -lt 4 ]; do
        bytes=$((bytes / 1024))
        unit=$((unit + 1))
    done

    echo "${bytes}${units[$unit]}"
}

echo -e "size\tpath\tnfs path"

TEMP_FILE=$(mktemp)

find $MODEL_PATH \( ! -size 0 -type f -o -type l \) -exec bash -c '
TEMP_FILE="$1"
shift
for f; do
  if [ -L "$f" ]; then
    target=$(readlink -f "$f")
    if [ -e "$target" ]; then
      size=$(du -h "$target" | cut -f1)
      bytes=$(du -b "$target" | cut -f1)
      echo -e "$size\t$f\t$target"
      echo "$bytes" >> "$TEMP_FILE"
    else
      echo "broken symlink: $f"
    fi
  else
    size=$(du -h "$f" | cut -f1)
    bytes=$(du -b "$f" | cut -f1)
    echo -e "$size\t$f"
    echo "$bytes" >> "$TEMP_FILE"
  fi
done
' _ "$TEMP_FILE" {} +

# 총 사이즈 계산
if [ -f "$TEMP_FILE" ]; then
    TOTAL_BYTES=$(awk '{sum += $1} END {print sum}' "$TEMP_FILE")
    TOTAL_SIZE=$(human_readable "$TOTAL_BYTES")
    FILE_COUNT=$(wc -l < "$TEMP_FILE")

    echo "----------------------------------------"
    echo -e "Total Size:\t$TOTAL_SIZE ($TOTAL_BYTES bytes)"
    echo -e "Total Files:\t$FILE_COUNT"

    rm "$TEMP_FILE"
fi
