#!/bin/bash
# Generate a database of JSON data from ID3 tags extracted from MP3 files.
# This includes extracting the cover art and associating it with the JSON data.
# --------------------------------------------------------------------------------

lib=".musiclib"
coverart="${lib}/coverart"
mkdir -p "${coverart}"

find . -iname "*.mp3" | while read file; do

    echo "Processing ${file}"

    # Get a UUID to uniquely identify the song.
    uuid=$(uuidgen)

    # Extract Cover Art, if any.
    ffmpeg -i "${file}" "${coverart}/${uuid}.png" 2>/dev/null

    # Extract ID3 data
    ffprobe -show_format -show_streams -print_format json "${file}" 2>/dev/null | jq .format.tags > ${lib}/${uuid}.json

    # Add the filename and covert art file to the extracted ID3 data.
    cat ${lib}/${uuid}.json | jq --arg file "${file}" '. + {file: $file}' > ${lib}/${uuid}.2
    mv ${lib}/${uuid}.2 ${lib}/${uuid}.json
    cat ${lib}/${uuid}.json | jq --arg coverart "${uuid}.png" '. + {covert: $coverart}' > ${lib}/${uuid}.2
    mv ${lib}/${uuid}.2 ${lib}/${uuid}.json

done 

# ls -l ${coverart}
# sleep 5
# cat ${lib}/*.json
