#!/usr/bin/bash
set -euo pipefail

# 🔧 Configuration
APPDATA_DIR="/opt/appdata"
OUTPUT_FILE="/opt/scripts_remote/upload/inventory/sqlite_inventory.csv"
mkdir -p "$(dirname "$OUTPUT_FILE")"

# 📄 Header CSV
echo "type,name,path,size_bytes" > "$OUTPUT_FILE"

command_exists() { command -v "$1" >/dev/null 2>&1; }

echo "📦 Scanning Docker containers for SQLite DBs in $APPDATA_DIR..."
echo "📝 Output CSV: $OUTPUT_FILE"

# --- Docker containers ---
if command_exists docker && docker ps >/dev/null 2>&1; then
  docker ps --format '{{.Names}}' | while read -r container; do
    echo "➡️  Inspecting Docker container: $container"

    # Chercher les fichiers liés à ce conteneur sous /opt/appdata
    db_files=$(find "$APPDATA_DIR" -type f -name '*.db' 2>/dev/null | grep "$container" || true)

    if [[ -n "$db_files" ]]; then
      while read -r path; do
        [[ -z "$path" ]] && continue
        size=$(stat -c %s "$path" 2>/dev/null || echo 0)
        echo "docker,$container,$path,$size" >> "$OUTPUT_FILE"
      done <<< "$db_files"
    else
      echo "   ⚠️  No .db files found in $APPDATA_DIR for $container"
    fi
  done
else
  echo "❌ Docker not available or not running"
fi

echo "✅ Inventory complete. Saved to: $OUTPUT_FILE"