#!/bin/bash

# Copyright © 2012-2026 ScriptFanix
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License.

# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.

# A copy of the GNU General Public License v3 is includded in the LICENSE file
# at the root of the project.

copyFiles_matching() {
	# Preserve the original file extension so the copy keeps its type
	# (e.g. .jpg, .png, .cue) regardless of any rename pattern applied to
	# the base name.
	local extension="${filename##*.}"
	# Try hardlink first (no extra disk space); fall back to a full data
	# copy if the source and destination are on different filesystems.
	if					\
	cp -al					\
		"$sourcepath/$filename"		\
		"${destinationpath[$destination]}/$destdir/$destfile.$extension"	\
		2>/dev/null			\
	|| cp -a				\
		"$sourcepath/$filename"		\
		"${destinationpath[$destination]}/$destdir/$destfile.$extension"
	then
		# Record the new destination path and copy the source
		# last_change timestamp via a subquery so the DB reflects when
		# the source was last modified.
		# old_filename captures the previous path so stale files can be
		# cleaned up later.
		echo							\
			"UPDATE	destination_files"			\
			"SET filename="					\
		"\"${destdir//\"/\"\"}/${destfile//\"/\"\"}.$extension\"," \
			"	last_change=("				\
			"		SELECT last_change"	 	\
			"		FROM source_files" 		\
			"		WHERE id=$fileid"		\
			"	),"					\
			"	old_filename=("				\
			"		SELECT filename"		\
			"		FROM destination_files"		\
			"		WHERE id=$destfileid"		\
			"	),"					\
			"	rename_pattern="			\
	"\"${destinationrenamepath[$destination]}/${destinationrename[$destination]}\","\
			"	fat32compat="				\
			"${destinationfat32compat["$destination"]},"	\
			"	ascii=${destinationascii["$destination"]}"\
			"WHERE  id=$destfileid;"			\
			>&3
		(( ++copies ))
	fi
}
