#!/bin/sh -e

# Invoke me thusly:
#   find srv -depth -exec ./shredname {} + | pv -ls $(find srv | wc -l) >/dev/null

tmp="$(mktemp -td chargen.XXXXXXXX)"
fifo="${tmp}/chargen.fifo"
chargen() {
  mkfifo "${fifo}"
  base64 < /dev/urandom | tr -dc 'A-Za-z0-9' > "${fifo}"
}
cleanup() {
  [ -z "${*}" ] || kill -TERM "${@}"
  rm -rf "${tmp}"
}

# Spawn chargen process
chargen &
pid=$!
trap "cleanup ${pid}; exit" EXIT
trap "echo Abort; exit" HUP INT TERM KILL

# Wait for chargen fifo to exist
while [ ! -e "${fifo}" ]
do
  sleep 0
done

# Open chargen fifo for reading
exec 3< "${fifo}"

while [ "${1}" ]
do
  dir="${1%/*}"
  [ "${dir}" != "${1}" ] || dir="."
  nym="${1##*/}"
  len="$(printf %s "${nym}" | wc -c)"
  #new="$(dd if=/dev/urandom bs=16 count=${len} 2>&- | base64 | tr -dc 'A-Za-z0-9' | cut -c1-${len})"
  #new="$(base64 < /dev/urandom | tr -dc 'A-Za-z0-9' | dd bs=${len} count=1 2>&-)" || true
  new="$(dd bs=${len} count=1 <&3 2>&-)" || true
  #echo "${dir}: ${nym} -> ${new} (${len})"
  mv -v "${dir}/${nym}" "${dir}/${new}"
  shift
done