#!/usr/bin/env sh
# Move files in the current directory into alphanumeric subdirs
#
# Flag | Description
# ---- | -----------
# -h   | Show this screen.
# -f   | Make changes to the file system (disable dry-run mode).
# -i   | Interactive. Don't overwrite existing files.
#
# Defaults to the eight letter groupings common in libraries. Choose your own
# groupings using (case insensitive) glob syntax:
#
#     alphamv A-M N-Z

dryrun=1
while getopts fihx opt; do
    case $opt in
    f) unset dryrun;;
    i) interactive=1;;
    h) awk 'NR == 1 {next} /^$/ {exit} {print substr($0, 3)}' "$0"; exit;;
    x) set -x;;
    esac
done
shift $(( OPTIND - 1 ))

if [ $# -eq 0 ]; then
    set -- '0-9' 'A-C' 'D-F' 'G-I' 'J-L' 'M-O' 'P-R' 'S' 'T-Z'
fi

for grp in "$@"; do
    test -z "$dryrun" && mkdir -p "$grp"
    lr -1 -t 'name != "'"$grp"'" && name ~~~ "['"$grp"']*"' -0 |
        xe -0 ${dryrun:+-n} -N0 mv ${interactive:+-i} {} "$grp"
done
