#!/usr/bin/env bash
# - needs "shuf", "wc", and "mktemp" from coreutils), "find" (from findutils),
#   and "ffmpeg" installed
# - silence files are located in subdir "silence/"
# - monster sound files are in subdir "sounds/"
# - the final mp3 files are stored in the current working dir
# - the final mp3 files are name "monster_XXXX.mp3" with four random characters

# test if dependency are available 
for dependency in shuf find wc ffmpeg mktemp; do
  if [ ! -x "$(which ${dependency})" ]; then
    echo "Error: ${dependency} not installed (correctly)" > /dev/stderr
    exit 1
  fi
done

REPEAT="4" # How often should a soundfile be included in the final MP3?

# make array of available silence files
SILENCE_FILES=($(find "silence/" -iname '*.mp3'))
if [ -z "${SILENCE_FILES}" ]; then
  echo "Error: no silence files found in 'silence/'" > /dev/stderr
  exit 2
else
  echo "Info: ${#SILENCE_FILES[@]} silence files found"
fi

# get mp3 filenames from subdir "sounds/" and shuffle them
SOUND_FILES=$(find sounds/ -iname '*.mp3')
if [ -z "${SOUND_FILES}" ]; then
  echo "Error: no sound files found in 'sounds/'" > /dev/stderr
  exit 3
else
  SF=$(echo ${SOUND_FILES} | wc -w)
  echo "Info: ${SF} sound files found"
fi

# create list of sound files separated by silence files
OUTPUT_FILE=$(mktemp -p ./ -t "monster_XXXX.mp3")
for i in ${REPEAT}; do
  cat <<EOF
${SOUND_FILES}
EOF
done | shuf | while read sound_file
    do
      echo "file '${sound_file}'"
      # add random silence
      silence_file=${SILENCE_FILES[$RANDOM % ${#SILENCE_FILES[@]} ]}
      echo "file '${silence_file}'"
    done \
| ffmpeg -f concat \
  -safe 0 \
  -i - -c copy \
  -loglevel fatal \
  -y "${OUTPUT_FILE}" \
&& echo "Info: monster sound file '${OUTPUT_FILE}' created. Have fun!"
