#!/bin/bash

# Extract mp3million .zip files into /mymount/sound/Music/<band>/<album>/*.mp3
# And					 .mp3 files into same

set -eu
set -o pipefail
set -x

original_cwd="$(pwd)"

for file in "$@"
do
    case "$file" in
        *.zip)
            # shellcheck disable=SC2001
            # Sat Apr 11 18:48:25 PDT 2020
            # Changed this so band would not include dashes
            # band=$(echo "$file" | sed 's/^\(.*\) - .*\.zip/\1/' )
            band=$(echo "$file" | sed 's/^\([^-]*\) - .*\.zip/\1/' )
            # shellcheck disable=SC2001
            album=$(echo "$file" | sed 's/^[^-]* - \(.*\)\.zip/\1/' )
            echo "$band" "$album"
            cd /mymount/sound/Music
            mkdir -p "$band"
            cd "$band"
            mkdir -p "$album"
            cd "$album"
            # -o says to overwrite - nice for reextraction
            unzip -o "$original_cwd"/"$file"
            cd "$original_cwd"
            ;;
        *.mp3|*.mp3.[0-9]|*.mp3.[0-9][0-9])
            # If we do not have ffprobe, do not continue
            if ! which ffprobe > /dev/null 2>&1
            then
                echo "$0: no ffprobe found" 1>&2
                exit 1
            fi
            # Strangely, ffprobe writes its output to stderr, not stdout.
            # We disable this shellcheck stuff, because I prefer a subprocess or 2 over the line noise that's
            # been getting into bash lately.
            # shellcheck disable=SC2001
            if ! band=$(ffprobe "$file" 2>&1 | grep -E '^ *artist ' | sed 's/^ *artist *: \(.*\)$/\1/')
            then
                band=$(ffprobe "$file" 2>&1 | grep -E '^ *album_artist ' | sed 's/^ *album_artist *: \(.*\)$/\1/')
            fi
            # shellcheck disable=SC2001
            album=$(ffprobe "$file" 2>&1 | grep -E '^ *album ' | sed 's/^ *album *: \(.*\)$/\1/')
            echo "$band" "$album"
            cd /mymount/sound/Music
            mkdir -p "$band"
            cd "$band"
            mkdir -p "$album"
            cd "$album"
            cp "$original_cwd"/"$file" "$file"
            cd "$original_cwd"
            ;;
        *)
            echo "$0: Unrecognized file extension on file $file" 1>&2
            exit 1
            ;;
    esac
done