#!/bin/bash

# Enable nullglob so the script doesn't throw errors if certain file types are missing
shopt -s nullglob

ORIGINAL_DIR="original"
CONVERTED_DIR="converted"

# 1. Create the new directory structure
mkdir -p $ORIGINAL_DIR $CONVERTED_DIR

# 2. Copy/move existing .mp3 and .m4a files to both directories without converting
mp3_m4a=(*.mp3 *.m4a)
if [ ${#mp3_m4a[@]} -gt 0 ]; then
  cp "${mp3_m4a[@]}" $ORIGINAL_DIR/
  mv "${mp3_m4a[@]}" $CONVERTED_DIR/
fi

# 3. Move .flac and .wav files to the 'original' directory
flac_wav=(*.flac *.wav)
if [ ${#flac_wav[@]} -gt 0 ]; then
  mv "${flac_wav[@]}" $ORIGINAL_DIR/
fi

# 4. Find and convert all .flac and .wav files inside the input directory
# We pass "$CONVERTED_DIR" right before the {} +
find "$ORIGINAL_DIR" -type f \( -name '*.flac' -o -name '*.wav' \) -exec bash -c '
  # Grab the first argument passed to this sub-shell and save it
  target_dir="$1"
  
  # "shift" discards the first argument ($1), so the remaining arguments ($@) 
  # are just the actual files provided by the find command.
  shift 
  
  for file; do
    mp3convert "$file" "$target_dir"
  done
' _ "$CONVERTED_DIR" {} +
