#!/bin/bash

########################################################################
#
# renameit.sh - rename files w/ a timestamp based on last modified time
#   written by Jason Baker (http://www.worldsworstsoftware.com)
#
########################################################################
#
# UPDATES:
# 2007/11/17
#  - safer file existence checking
# 2007/02/12
#  - fixed bug with multiple periods in file name or path name
# 2006/10/25
#  - updated usage info
#  - replaced dos2unix usage w/ tr
#  - cleaned up some test statements
# 2006/9/14
#  - initial version
#
########################################################################


function print_usage()
{
	echo "renameit.sh - rename files w/ a timestamp based on file's last modified time"
	echo
	echo "USAGE"
	echo "  renameit.sh PATH"
	echo
	echo "ARGUMENTS"
	echo "  PATH - the path to files to check"
	echo
	echo "NOTES"
	echo "  Only files located directly within the directory specified will be renamed."
	echo
	echo
	echo "  ERROR: $1"
	exit 1
}


if  test -z "$1"
then
	print_usage "Invalid arguments specified."
fi

if test ! -d "$1"
then
	print_usage "$1 is not a directory."
fi

FILE_COUNTER=1

BASE_PATH="${1%*/}/" #this will put a / on the end of the path if there isnt one already

#
# thanks to http://www.vasudevaservice.com/documentation/how-to/converting_dos_and_unix_text_files
# for help w/ dos2unix to TR convert tip
#

FILES=`find "$1" -maxdepth 1 -type f -name '*' | sort | tr -d '\15\32'`

#make for's argument seperator newline only
IFS=$'\n'

for FILE in $FILES
do
	echo "renaming $FILE"
	FILENAME=`basename "$FILE"`
	SUFFIX_POS=`expr index "$FILENAME" ".*\(.\)"`

	FILE_SUFFIX=".${FILENAME:SUFFIX_POS}"

    	FILE_DATE=`find "$FILE" -printf "%TY%Tm%Td %TH%TM%TS"`
	
	NEW_FILE="$BASE_PATH$FILE_DATE$FILE_SUFFIX"

	#make sure a file with the new name doesn't already exist

	echo "trying $NEW_FILE"
	while [ -e "$NEW_FILE" ]
	do
	  echo "file $NEW_FILE already exists, trying something else.."
   	  #the file already exists, lets try to make it unique..
	  NEW_FILE="$BASE_PATH$FILE_DATE $FILE_COUNTER$FILE_SUFFIX"
	  ((FILE_COUNTER=FILE_COUNTER + 1))
	  echo "trying $NEW_FILE"
	done
	
	FILE_COUNTER=1;
	
	echo "Renaming File: $FILE"
	echo "  to: $NEW_FILE"
	echo

	mv "$FILE" "$NEW_FILE"	
done

