#!/bin/bash
getFiles() {
	scantime=$EPOCHSECONDS
	for prune_expression in "${skippeddirectories[@]}"
	do
		prunes+=( -path "$sourcepath$prune_expression" -prune -o )
	done
	(( cron )) || echo -n "Scanning $sourcepath...  "
	# We probably have thousands of files, don't waste time on disk writes
	echo 'BEGIN TRANSACTION;' >&3
	while read -d $'\0' time size filename
	do
		if (( skip_us_timestamp ))
		then
			compare_time=${time%.*}.%
		else
			compare_time=$time
		fi
		if ! Select source_files id >/dev/null <<-EOWhere
				filename = ${filename//$'\n'/::AtOM:NewLine:SQL:Inline::}
				mime_type > 0
				last_change LIKE $compare_time
				size = $size
			EOWhere
		then
			mimetype=$(file -b --mime-type "$sourcepath/$filename")
			if [[ $mimetype == application/ogg ]] || [[ $mimetype == audio/ogg ]]
			then
				case "$(head -n5 "$sourcepath/$filename" | tr -d '\0')" in
					*'vorbis'*)
						mimetype+=' vorbis'
					;;
					*'OpusHead'*)
						mimetype+=' opus'
					;;
				esac
			fi
			mimetypeid=$(
				InsertIfUnset mime_types <<-EOInsert
					mime_text $mimetype
				EOInsert
			)
			InsertOrUpdate source_files	\
				last_change $time	\
				size $size		\
				last_seen $scantime	\
				mime_type $mimetypeid	\
				>/dev/null		\
			<<-EOWhere
				filename ${filename//$'\n'/::AtOM:NewLine:SQL:Inline::}
			EOWhere
			(( ++new ))
			if (( new % 1000 == 0 ))
			then
				echo 'COMMIT;BEGIN TRANSACTION;' >&3
				(( debug ))	\
				&& echo -ne "\bCommitted $count files...  "
			fi
		else
			Update source_files last_seen $scantime <<-EOWhere
				filename = ${filename//$'\n'/::AtOM:NewLine:SQL:Inline::}
			EOWhere
		fi
		progressSpin
	done < <(
		find "$sourcepath" "${prunes[@]}" -type f -not -name '.*' -printf "%T@ %s %P\0"
	)
	echo 'COMMIT;' >&3
	(( cron )) || echo -n $'\r'
	if (( count ))
	then
		echo "$count files found${new:+, $new new or changed}."	\
			$'\033[K'
	fi
	unset count
}
