#!/usr/bin/env bash set -o errexit -o noclobber -o nounset -o pipefail codec=copy extension=m4a mode=chaptered GREP=$(grep --version | grep -q GNU && echo "grep" || echo "ggrep") if ! [[ $(type -P "$GREP") ]]; then echo "$GREP (GNU grep) is not in your PATH" echo "Without it, this script will break." echo "On macOS, you may want to try: brew install grep" exit 1 fi if [ "$#" -eq 0 ]; then echo "Usage: bash AAXtoM4A [--single] AUTHCODE {FILES}" exit 1 fi if [[ "$1" == '--single' ]] then mode=single shift fi if [ ! -f .authcode ]; then auth_code=$1 shift else auth_code=`head -1 .authcode` fi debug() { echo "$(date "+%F %T%z") ${1}" } trap 'rm -r -f "${working_directory}"' EXIT working_directory=`mktemp -d 2>/dev/null || mktemp -d -t 'mytmpdir'` metadata_file="${working_directory}/metadata.txt" save_metadata() { local media_file media_file="$1" ffprobe -i "$media_file" 2> "$metadata_file" } get_metadata_value() { local key key="$1" normalize_whitespace "$($GREP --max-count=1 --only-matching "${key} *: .*" "$metadata_file" | cut -d : -f 2- | sed -e 's#/##g;s/ (Unabridged)//' | tr -s '[:blank:]' ' ')" } get_bitrate() { get_metadata_value bitrate | $GREP --only-matching '[0-9]\+' } normalize_whitespace() { echo $* } for path do debug "Decoding ${path} with auth code ${auth_code}..." save_metadata "${path}" genre=$(get_metadata_value genre) artist=$(get_metadata_value artist) title=$(get_metadata_value title) output_directory="$(dirname "${path}")/${genre}/${artist}/${title}" mkdir -p "${output_directory}" full_file_path="${output_directory}/${title}.${extension}"