#!/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	\
|| {
	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 'D' opt
do
	case $opt in
		D)	(( debug++ ))	;;
	esac
done

getConfig
sanityCheck
openDatabase

sourcepath=''


for destination in ${!destinationpath[@]}
do
	case ${destinationformat[$destination]} in
		ogg) mimetype='audio/ogg vorbis' ;;
		opus) mimetype='audio/ogg opus' ;;
		mp3) mimetype='audio/mpeg' ;;
	esac
	while read filename
	do
		getTags
		expr='^[0-9]+$'
		if [[ $genre =~ $expr ]]
		then
			echo "$filename ($genre)"
			Update destination_files last_change 0 <<-EOWhere
				filename = $filename
			EOWhere
		fi
	done < <(
		find "${destinationpath[$destination]}"	\
				-name '*.ogg'		\
			-o	-name '*.mp3'		\
			-o	-name '*.opus'
		)
done

closeDatabase
