#!/usr/bin/env bash
# Sort .sms ROMs into folders by first character:
#   A-Z      -> A/ .. Z/
#   0-9      -> 0-9/
#   [BIOS]   -> BIOS/
#   anything else -> #/
#
# Usage: ./sort_roms.sh [directory]   (defaults to the current directory)
#        DRY_RUN=1 ./sort_roms.sh     (show what would be moved)

set -euo pipefail
shopt -s nullglob nocaseglob

dir="${1:-.}"
cd "$dir"

moved=0
for f in *.sms; do
    [[ -f "$f" ]] || continue

    first="${f:0:1}"
    if [[ "$f" == "[BIOS]"* ]]; then
        dest="BIOS"
    elif [[ "$first" =~ [A-Za-z] ]]; then
        dest="${first^^}"
    elif [[ "$first" =~ [0-9] ]]; then
        dest="0-9"
    else
        dest="#"
    fi

    if [[ -n "${DRY_RUN:-}" ]]; then
        echo "$dest/  <-  $f"
    else
        mkdir -p -- "$dest"
        mv -n -- "$f" "$dest/"
    fi
    moved=$((moved + 1))
done

echo "Processed $moved ROM(s)."
