#!/bin/bash
# videos_by_size.sh
# Finds every video file on your drive and creates a folder of links to them,
# named so that Finder (sorted by Name) lists them from largest to smallest.
#
# Usage:
#   chmod +x videos_by_size.sh
#   ./videos_by_size.sh                      # scan / , output to ~/Desktop/Videos_by_size
#   ./videos_by_size.sh ~/Movies             # scan only a specific folder
#   ./videos_by_size.sh / ~/Desktop/MyLinks  # custom scan root and output folder
#   FINDER_ALIASES=1 ./videos_by_size.sh     # create real Finder aliases (slower)
#
# Tip: grant Terminal "Full Disk Access" (System Settings > Privacy & Security)
# to avoid missing files in protected folders.
# Save Space! Bon Chance! www.pibr.fr

ROOT="${1:-/}"
OUT="${2:-$HOME/Desktop/Videos_by_size}"

mkdir -p "$OUT"
# Clear old links from a previous run (only links, never real files)
find "$OUT" -maxdepth 1 \( -type l -o -name '*.alias' \) -delete 2>/dev/null

echo "Scanning $ROOT for videos... (this can take several minutes)"

EXTS=(mp4 mov m4v mkv avi wmv flv webm mpg mpeg mts m2ts mxf r3d braw prores ogv 3gp vob ts)
NAME_ARGS=()
for e in "${EXTS[@]}"; do
  NAME_ARGS+=(-o -iname "*.$e")
done
NAME_ARGS=("${NAME_ARGS[@]:1}")   # drop the leading -o

human() {
  awk -v b="$1" 'BEGIN{
    split("B KB MB GB TB", u, " "); i=1;
    while (b>=1024 && i<5) { b/=1024; i++ }
    printf("%.1f%s", b, u[i])
  }'
}

rank=0
find "$ROOT" \
  \( -path /System -o -path /Volumes -o -path /dev -o -path /private/var \
     -o -path "$OUT" -o -path '*/.Trashes' -o -path '*/node_modules' \) -prune -o \
  -type f \( "${NAME_ARGS[@]}" \) -print0 2>/dev/null \
| xargs -0 stat -f '%z	%N' 2>/dev/null \
| sort -rn \
| while IFS=$'\t' read -r size path; do
    rank=$((rank + 1))
    base="$(basename "$path")"
    link="$OUT/$(printf '%04d' "$rank")_$(human "$size")_${base}"
    if [ "${FINDER_ALIASES:-0}" = "1" ]; then
      osascript -e "tell application \"Finder\" to make alias file to POSIX file \"$path\" at POSIX file \"$OUT\" with properties {name:\"$(basename "$link").alias\"}" >/dev/null 2>&1
    else
      ln -s "$path" "$link"
    fi
    echo "$rank  $(human "$size")  $path"
  done | tee "$OUT/_index.txt" | tail -n 25

echo
echo "Done. Links are in: $OUT"
echo "Full list (largest first): $OUT/_index.txt"
