#!/bin/bash
# scan.sh — Drop this in a directory alongside index.html
# Run it to generate manifest.json from all subdirectories
# that contain a title.txt and/or thumbnail.png

DIR="$(cd "$(dirname "$0")" && pwd)"
MANIFEST="$DIR/manifest.json"

echo '[' > "$MANIFEST"
FIRST=true

for d in "$DIR"/*/; do
  [ -d "$d" ] || continue
  name="$(basename "$d")"

  # Skip hidden dirs and common non-content dirs
  [[ "$name" == .* ]] && continue
  [[ "$name" == "node_modules" ]] && continue

  # Read title.txt if it exists, otherwise use folder name
  if [ -f "$d/title.txt" ]; then
    title="$(head -1 "$d/title.txt" | sed 's/"/\\"/g')"
  else
    title="$name"
  fi

  # Read optional description (2nd line of title.txt)
  description=""
  if [ -f "$d/title.txt" ]; then
    description="$(sed -n '2p' "$d/title.txt" | sed 's/"/\\"/g')"
  fi

  # Check for thumbnail
  has_thumb=false
  thumb_file=""
  for ext in png jpg jpeg gif webp svg; do
    if [ -f "$d/thumbnail.$ext" ]; then
      has_thumb=true
      thumb_file="thumbnail.$ext"
      break
    fi
  done

  # Get modified date
  mod_date="$(date -r "$d" '+%Y-%m-%d' 2>/dev/null || date '+%Y-%m-%d')"

  # Count files in subdirectory
  file_count="$(find "$d" -maxdepth 1 -type f | wc -l | tr -d ' ')"

  if [ "$FIRST" = true ]; then
    FIRST=false
  else
    echo ',' >> "$MANIFEST"
  fi

  cat >> "$MANIFEST" <<EOF
  {
    "folder": "$name",
    "title": "$title",
    "description": "$description",
    "thumbnail": "$thumb_file",
    "modified": "$mod_date",
    "files": $file_count
  }
EOF

done

echo ']' >> "$MANIFEST"

echo "✓ Scanned $(grep -c '"folder"' "$MANIFEST") directories → manifest.json"
