#!/bin/bash -
#===============================================================================
#
#         FILE: show_queue
#
#        USAGE: ./show_queue
#
#  DESCRIPTION: Show the pending queue, expanding each album's details from
#               the database.
#
#               / This version calls sqlite3 once and feeds it queries in a loop /
#
#      OPTIONS: ---
# REQUIREMENTS: ---
#         BUGS: ---
#        NOTES: ---
#       AUTHOR: Dave Morriss (djm), Dave.Morriss@gmail.com
#      VERSION: 0.2.1
#      CREATED: 2020-09-15 12:38:03
#     REVISION: 2021-08-05 16:39:05
#
#===============================================================================

set -o nounset                              # Treat unset variables as an error

SCRIPT=${0##*/}
#DIR=${0%/*}

VERSION='0.2.1'

#
# Files and directories
#
BASEDIR="$HOME/MusicDownloads"
DATADIR="$BASEDIR/Magnatune_Data"
SCRIPTDIR="$BASEDIR/magnatune-downloader"

QUEUE="$SCRIPTDIR/pending"
DB="$DATADIR/sqlite_normalized.db"

#
# Sanity checks
#
[ -e "$QUEUE" ] || { echo "$QUEUE not found"; exit 1; }

#
# Check the queue contains data
#
if [[ ! -s $QUEUE ]]; then
    echo "$SCRIPT($VERSION): there is nothing in the queue"
    exit
fi

RE='^http://magnatune.com/artists/albums/([A-Za-z0-9-]+)/?$'

#
# Template SQL for printf
#
SQLtemplate=$(cat <<ENDSQL1
SELECT
    ar.name AS Artist,
    al.name AS Album,
    group_concat(distinct ge.name) AS 'Genre',
    group_concat(distinct sg.name) AS 'Subgenre',
    al.sku as Code
FROM albums al
JOIN artists ar ON al.artist_id = ar.artists_id
JOIN genres_albums ga on al.album_id = ga.album_id
JOIN genres ge ON ge.genre_id = ga.genre_id
JOIN subgenres_albums sa on al.album_id = sa.album_id
JOIN subgenres sg ON sg.subgenre_id = sa.subgenre_id
GROUP BY al.album_id
HAVING sku = '%s';
.print '--------'
ENDSQL1
)

#
# Start the coprocess
#
coproc dbproc { stdbuf -i0 -o0 sqlite3 -line "$DB"; }

#
# Read and report the queue elements.
#
n=0
while read -r URL; do
    ((n++))

    if [[ $URL =~ $RE ]]; then
        SKU="${BASH_REMATCH[1]}"
    else
        echo "Problem parsing URL in queue (line $n): $URL"
        continue
    fi

    #
    # Build the query and write it to the coprocess
    #
    # shellcheck disable=SC2059
    printf "$SQLtemplate\n" "$SKU" >&"${dbproc[1]}"

done < "$QUEUE"

#
# Close the input pipe (a file descriptor move documented as '[n]>&digit-'
# which "moves the file descriptor digit to file descriptor n, or the standard
# output (file descriptor 1) if n is not specified". There is no digit here,
# so presumably /nothing/ is being moved to the file descriptor in dbproc[1].
#
exec {dbproc[1]}>&-

#
# Collect everything from the coprocess
#
cat <&"${dbproc[0]}"

# vim: syntax=sh:ts=8:sw=4:ai:et:tw=78:fo=tcrqn21
