#!/bin/sh
#
# Fri 23 May 2025
#
# randmv takes a directory and a list of words, and randomly renames the files
# in the directory using that list. It (in theory) has no duplicates, assuming
# the word list is suitably unique. It works for /usr/share/dict/words, it just
# takes a while to sort
#
# WARNING: This script will fuck shit up, use with extreme caution
#
# source: https://patpatpat.xyz/data/randmv

usage() {
  echo 'usage: randmv -f FILES -w WORDS [-n]'
  exit 1
}

args=$(getopt nf:w: $*)

if [ $? -ne 0 ]; then
  usage
fi

set -- $args

while [ $# -ne 0 ]; do
  case "$1" in
    -n)
      dry="$1"
      shift
      ;;
    -f)
      dir="$2"
      shift 2
      ;;
    -w)
      words="$2"
      shift 2
      ;;
    --)
      shift
      break
      ;;
  esac
done

if [ -z $dir ] || [ -z $words ]; then
  usage
fi

if [ ! -d $dir ] || [ ! -r $words ]; then
  usage
fi

files=$(ls $dir)
nfiles=$(($(echo "$files" | wc -l)))

words=$(sort -R $words | head -n $nfiles)
nwords=$(($(echo "$words" | wc -l)))

if [ $nwords -lt $nfiles ]; then
  echo "error: not enough words ($nwords < $nfiles)"
  exit 1
fi

for file in $files; do
  words=$(echo "$words" | head -n $nwords)
  nwords=$((nwords - 1))
  word=$(echo "$words" | tail -n 1 | tr '[:upper:]' '[:lower:]')
  ext="${file##*.}"

  if [ "$ext" != "$file" ]; then
    word="$word.$ext"
  fi

  echo "mv $dir/$file $dir/$word"

  if [ -z $dry ]; then
    mv "$dir/$file" "$dir/$word" || exit 1
  fi
done
