#!/bin/bash
CH="/root/ce-channels"

for channel_dir in "$CH"/*/; do
  name=$(basename "$channel_dir")
  converted=0

  for link in $(find "$channel_dir" -maxdepth 1 -type l 2>/dev/null); do
    target=$(readlink "$link")
    linkname=$(basename "$link")

    # Remove the symlink
    rm "$link"

    # Create real directory
    mkdir -p "$channel_dir/$linkname"

    # Symlink individual files inside
    find "$target" -maxdepth 1 -type f 2>/dev/null | while read f; do
      ln -sf "$f" "$channel_dir/$linkname/$(basename "$f")"
    done

    # Symlink subdirectories inside
    find "$target" -maxdepth 1 -type d -not -path "$target" 2>/dev/null | while read d; do
      ln -sf "$d" "$channel_dir/$linkname/$(basename "$d")"
    done

    converted=$((converted + 1))
  done

  if [ "$converted" -gt 0 ]; then
    subdirs=$(find "$channel_dir" -maxdepth 1 -type d -not -path "$channel_dir" | wc -l | tr -d ' ')
    echo "$name: $converted symlinks → real dirs ($subdirs subdirs total)"
  fi
done

echo ""
echo "=== DONE ==="
total=$(find "$CH" -mindepth 2 -maxdepth 2 -type d | wc -l | tr -d ' ')
echo "Total browsable subdirectories: $total"
