#!/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 'rD' opt
do
	case $opt in
		r)	remove=1	;;
		D)	(( debug++ ))	;;
	esac
done

getConfig
sanityCheck
openDatabase

for destination in "${!destinationpath[@]}"
do
	echo -ne "\rScanning destination $destination...  \033[K"
	while read -r -d $'\0' filename
	do
		sqlfile=${filename//$'\n'/::AtOM:NewLine:SQL:Inline::}
		if ! Select destination_files id	\
			>/dev/null			\
			<<<"filename = ${sqlfile#${destinationpath["$destination"]}/}"
		then
			echo -e $'\r'"$filename\033[K"
			(( remove )) && rm "$filename"
			echo -n "Scanning destination $destination...  "
		fi
		progressSpin
	done < <(find "${destinationpath["$destination"]}" -type f -print0)
done
echo -en "\r\033[K"

closeDatabase
