#!/bin/sh -e
#
#    pictor-unload: a script for unloading pictures from one directory
#                   to another, and renaming them with their timestamp
#                   for ordering and interleaving
#    Copyright (C) 2010 Dustin Kirkland <dustin.kirkland@gmail.com>
#
#    This program is free software: you can redistribute it and/or modify
#    it under the terms of the GNU Affero General Public License as published by
#    the Free Software Foundation, 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 Affero General Public License for more details.

#    You should have received a copy of the GNU Affero General Public License
#    along with this program.  If not, see <http://www.gnu.org/licenses/>.
#

SOURCE=$(echo "$1" | sed -e "s:/\+$::")
DEST=$(echo "$2" | sed -e "s:/\+$::")

# Clean up file names
pictor-rename "$SOURCE/"*
# Copy pictures over, incrementally
echo "INFO: Copying images..."
rsync -aP "$SOURCE"/ "$DEST"/
# Remove any duplicates
echo "INFO: Removing duplicates..."
fdupes -m "$DEST"
fdupes -r -N "$DEST"
# Ensure picture names are clean
pictor-rename "$DEST/"*
# Ensure permissions are sane
echo "INFO: Fixing permissions..."
find "$DEST" -type f -exec chmod 644 {} \;
find "$DEST" -type d -exec chmod 755 {} \;
echo "INFO: Syncing to disk..."
sync
d="$(date +%Y-%m-%d_%H-%M-%S)"
echo
echo -n "Do you want to rename [${SOURCE}] to [${SOURCE}.${d}]? [y/N]: "
answer=$(head -n 1)
case "$answer" in
	y*|Y*)
		# Rename SOURCE to mark as unloaded
		mv -f "${SOURCE}" "${SOURCE}.${d}"
	;;
esac
echo
sync
