#!/usr/bin/env bash

declare -r				\
	DOCDIR=%DOCDIR%			\
	LIBDIR=%LIBDIR%			\
	SHAREDIR=%SHAREDIR%
declare -r				\
	exampleconf=$DOCDIR/example.cfg	\
	schema=$SHAREDIR/schema.sql	\
					\
	oldIFS="$IFS"

## Define exit codes
source "$SHAREDIR"/errorcodes

# config structures
declare -A			\
	destinationchannels	\
	destinationfat32compat	\
	destinationcopymime	\
	destinationformat	\
	destinationfrequency	\
	destinationid		\
	destinationloss		\
	destinationmaxbps	\
	destinationnormalize	\
	destinationpath		\
	destinationquality	\
	destinationrename	\
	destinationnoresample	\
	destinationrenamepath	\
	destinationskipmime	\
	checks			\
|| {
	echo "Check your Bash version. You need >= 4.0" >&2
	exit $EBASHVERS
}

LC_ALL=C

shopt -s extglob

for function in "$LIBDIR"/*/*
do
	source "$function"
done

if ! [[ -f "${XDG_CONFIG_HOME:-$HOME/.config}/AtOM/atom.cfg" ]]	\
&& [[ -f "$HOME/.atom/atom.cfg" ]]
then
	echo	"Configuration found in legacy location $HOME/.atom/atom.cfg."\
		"Migrating configuration and data to XDG standard"
	xdgMigrate
fi
cffile="${XDG_CONFIG_HOME:-$HOME/.config}/AtOM/atom.cfg"

while getopts 'AlacdgptnNyuD' opt
do
	case $opt in
		A)	checks[albumartist]=1	;;
		l)	checks[album]=1		;;
		a)	checks[artist]=1	;;
		c)	checks[composer]=1	;;
		d)	checks[disc]=1		;;
		g)	checks[genre]=1		;;
		p)	checks[performer]=1	;;
		t)	checks[title]=1		;;
		n)	checks[track]=1		;;
		N)	checks[tracktotal]=1	;;
		y)	checks[year]=1		;;

		u)	update=1		;;
		D)	(( debug++ ))		;;
	esac
done

(( ${#checks[@]} )) || {
	cat >&2 <<-EOHelp
		No check specified!
		    -A Album artist
		    -l Album
		    -a Artist
		    -c Composer
		    -d Disc
		    -g Genre
		    -p Performer
		    -t Title
		    -n Track number
		    -N Track total
		    -y Year

		Other options:
		    -u Update database first
		    -D Debug
	EOHelp
	exit 1
}

getConfig
sanityCheck
openDatabase

if (( update ))
then
	getFiles
	updateMimes
	updateTags
fi

for check in ${!checks[@]}
do
	case $check in
		tracktotal)
			whereclause+="${whereclause+OR }NOT tags.track LIKE \"%/%\""
		;;
		*)
			whereclause+="${whereclause+OR }tags.$check IS NULL"
		;;
	esac
	whereclause+='
'
done

cat >&3 <<-EOSelect
	SELECT	source_files.filename,
		tags.genre,
		tags.albumartist,
		tags.year,
		tags.album,
		tags.disc,
		tags.artist,
		tags.track,
		tags.title,
		tags.composer,
		tags.performer
	FROM			tags
		INNER JOIN	source_files
			ON	tags.source_file=source_files.id
		INNER JOIN	mime_types
			ON	source_files.mime_type=mime_types.id
	WHERE	(
			$whereclause
		)
	AND NOT	tags.tagreader LIKE "unknown-%"
	AND NOT	mime_types.mime_text LIKE "text/%"
	AND NOT	mime_types.mime_text LIKE "image/%"
	;

	SELECT	"AtOM:NoMoreFiles";
EOSelect

read -u4 -r -d $'\0' line
until [[ $line == AtOM:NoMoreFiles ]]
do
	lines+=( "$line" )
	read -u4 -r -d $'\0' line
done

for line in "${lines[@]}"
do
	missing=()
	filename=${line%%::AtOM:SQL:Sep::*}
	rest="${line#*::AtOM:SQL:Sep::}::AtOM:SQL:Sep::"
	(( ${checks[genre]} )) && [ -z "${rest%%::AtOM:SQL:Sep::*}" ] && missing+=( "Genre" )
	rest=${rest#*::AtOM:SQL:Sep::}
	(( ${checks[albumartist]} )) && [ -z "${rest%%::AtOM:SQL:Sep::*}" ] && missing+=( "AlbumArtist" )
	rest=${rest#*::AtOM:SQL:Sep::}
	(( ${checks[year]} )) && [ -z "${rest%%::AtOM:SQL:Sep::*}" ] && missing+=( "Year" )
	rest=${rest#*::AtOM:SQL:Sep::}
	(( ${checks[album]} )) && [ -z "${rest%%::AtOM:SQL:Sep::*}" ] && missing+=( "Album" )
	rest=${rest#*::AtOM:SQL:Sep::}
	(( ${checks[disc]} )) && [ -z "${rest%%::AtOM:SQL:Sep::*}" ] && missing+=( "Disc" )
	rest=${rest#*::AtOM:SQL:Sep::}
	(( ${checks[artist]} )) && [ -z "${rest%%::AtOM:SQL:Sep::*}" ] && missing+=( "Artist" )
	rest=${rest#*::AtOM:SQL:Sep::}
	track=${rest%%::AtOM:SQL:Sep::*}
	(( ${checks[track]} )) && [ -z "$track" ] && missing+=( "Track" )
	if (( ${checks[tracktotal]} )) && ! [[ $track =~ / ]]
	then
		missing+=( TrackTotal )
	fi
	rest=${rest#*::AtOM:SQL:Sep::}
	(( ${checks[title]} )) && [ -z "${rest%%::AtOM:SQL:Sep::*}" ] && missing+=( "Title" )
	rest=${rest#*::AtOM:SQL:Sep::}
	(( ${checks[composer]} )) && [ -z "${rest%%::AtOM:SQL:Sep::*}" ] && missing+=( "Composer" )
	rest=${rest#*::AtOM:SQL:Sep::}
	(( ${checks[performer]} )) && [ -z "${rest%%::AtOM:SQL:Sep::*}" ] && missing+=( "Performer" )
	rest=${rest#*::AtOM:SQL:Sep::}
	echo "$filename: ${missing[@]}"
done

closeDatabase
