#!/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:/\+$::")
TIMESTAMP=$(date +%Y%m%d%H%M%S)
if df -h -P "$SOURCE" | grep -qs "/media/"; then
	# If source is on a /media device, offer to unmount when done
	MOUNT=$(df -h -P "$SOURCE" | tail -n1 | awk '{print $1}')
fi

for i in "$SOURCE"/*; do
	t=$(stat "$i" | grep "^Modify: " | awk '{print $2 "_" $3}' | sed -e "s/\..*/__/")
	b=$(basename "$i")
	cp -av "$i" "$DEST"/"$t$b"
	chmod -x "$DEST"/"$t$b"
done
mv -v "$SOURCE" "$SOURCE"."$TIMESTAMP"
sync

if [ -b "$MOUNT" ]; then
	echo -n "Do you want to unmount the source media on [$MOUNT]? [y/N] "
	unmount=$(head -n 1)
	if [ "$unmount" = "Y" ] || [ "$unmount" = "y" ]; then
		sudo umount -v "$MOUNT"
	fi
fi
echo "Success!"
