#!/bin/bash

guessPath() {
	echo 'SELECT IFNULL( (
		SELECT	destination_files.last_change
		FROM		destination_files
		INNER JOIN	source_files
			ON	destination_files.source_file_id=source_files.id
		INNER JOIN	mime_type_actions
			ON
			mime_type_actions.id=source_files.mime_type
		INNER JOIN	destinations
			ON	destinations.id=destination_files.destination_id
		WHERE	destinations.id = '$destinationid'
		AND	source_files.filename LIKE
				"'"${sourcedir//\"/\"\"}"'/%"
		AND NOT	source_files.filename LIKE
				"'"${sourcedir//\"/\"\"}"'/%/%"
		AND	mime_type_actions.action = 1
		ORDER BY destination_files.last_change DESC
		LIMIT 1
	),"0.0");
	'>&3
	read -u4 -r -d $'\0' timestamp
	if (( ${timestamp/./} == 0 ))
	then
		return 2
	fi
	echo 'SELECT IFNULL( (
		SELECT	destination_files.filename
		FROM		destination_files
		INNER JOIN	source_files
			ON	destination_files.source_file_id=source_files.id
		INNER JOIN	mime_type_actions
			ON
			mime_type_actions.id=source_files.mime_type
		INNER JOIN	destinations
			ON	destinations.id=destination_files.destination_id
		WHERE	destinations.id = '$destinationid'
		AND	source_files.filename LIKE
				"'"${sourcedir//\"/\"\"}"'/%"
		AND NOT	source_files.filename LIKE
				"'"${sourcedir//\"/\"\"}"'/%/%"
		AND	mime_type_actions.action = 1
		ORDER BY destination_files.last_change DESC
		LIMIT 1
	),"AtOM:NotFound");
	'>&3
	read -u4 -r -d $'\0' filename
	if [[ $filename != AtOM:NotFound ]]
	then
		echo "${filename%/*}"
	else
		return 1
	fi
}
