#!/bin/bash
# rmw - ReMove to Waste
# Author: Andy Alt ( http://sourceforge.net/projects/rmw/ )
# License: GPL
# Description: ReMove to Waste, rmw, is a bash script.
# It functions as a Linux/Unix console recycle bin when
# reMoving files with rm. ReMove to Waste will move files
# to a Waste folder or "Trash can," and it will prepend
# the time and date to files when reMoving them. It keeps a
# "history" to easily copy files back to their previous location.
# 
# WARNING: Use this script at your own risk.

# Change this to set the location of the rmw configuration directory
RMWCONF=${HOME}/.rmw

release_date="June 29, 2009"
VERSION="svn-"$release_date"-3"
#VERSION="0.971 Released $release_date"

debug=1
# Other variables can be found in the file rmwrc (which will be created
# after this script has been run once) in your rmw config directory

displayver() {
	echo -e "\nReMove to Waste $VERSION\n"
}

displayhelp() {

echo ""
echo "usage: rmw [option(s)] <file1> <file2>"
echo ""
echo "-v / be verbose"
echo "-i / interactive"
echo "-f / force, no prompting"
echo "-r / directory recursion"
echo "-K / Use KDE Trash"
echo "-u / undo last ReMove"
echo "-V / display version"
echo ""
 } 


if [ $# -eq 0 ]; then
	displayhelp
	exit 0
fi

#
# This doesn't work.
#
# real_rm() {
# echo ""
# echo "Executing /bin/rm"
# /bin/rm $@
# exit 2
#  }

mvargs="-"
KDETrash=0

while getopts ":ivfrKuhV" Option
do

case $Option in
    i     ) mvargs=$mvargs"i";;
    v     ) mvargs=$mvargs"v";;
    f     ) mvargs=$mvargs"f";;
    r     ) ;;
    V     ) displayver;exit 0;;
    u	) doundo=1;;
    K	) KDETrash=1;;
    h	) displayhelp;;
#    e   ) real_rm;;		
    *     ) echo "";echo "Unimplemented option chosen.";displayhelp;exit 1;;   # DEFAULT
  esac
done

shift $(($OPTIND - 1))

if [ $mvargs == "-" ]; then
	mvargs=""
fi

	if [ $doundo ]; then
		source ${RMWCONF}/undofile-last
		exit 0
	fi

#if [ $debug = 1 ]; then
	
#fi



# Create config dir if it doesn't exist
if [ ! -d ${RMWCONF} ]; then
	echo ""
	mkdir -pv ${RMWCONF}
	
	if [ ! -d ${RMWCONF} ]; then
		echo "Unable to read/write configuration directory!*"
		exit 1
	fi
fi

# Create configuration file if it doesn't exist
#
#
if [ ! -e ${RMWCONF}/rmwrc ]; then
echo ""
echo "Creating rmw configuration file ${RMWCONF}/rmwrc"
cat > ${RMWCONF}/rmwrc << "EOF"
#
# This config file should be created when you run rmw
# the first time
WASTE=${HOME}/.Waste
# After running rmw x times, disk usage of Waste directory will
# be displayed. Use 0 to disable
showdu=10
#
# Number of undo files to keep
num_undofiles=20
#
# Use verbosity even if it's not passed on the command line
# 0 or 1 to disable/enable
verbosity=1
#
# Display version at runtime, 0 or 1 to disable/enable
showver=1
#
# Use KDE Trash, 0 or 1 to disable/enable
useKDETrash=0
# Using the KDE Trash folder won't work unless the
# path below is correct. Only enable it above if you
# know for sure that it's correct.
KDETrashFolder="$HOME/.local/share/Trash"
# KDE has a trashrc file that says if the trash is empty
# or not. This may be different on some systems.
KDEtrashrc="$HOME/.kde/share/config/trashrc"
EOF
fi


#
# If -K was passed on the command line,
# the option to use KDETrash will be overwritten when the conf
# file is read. Storing it here in a temp var
#

# Read in variables from configuration file
source ${RMWCONF}/rmwrc
#


# If -K was passed on the command line, this will assign the
# value of '1' to useKDETrash regardless of its setting in the
# conf file
#

if [ $KDETrash = 1 ]; then
	useKDETrash=1
fi


if [ ! $verbosity ]; then
cat >> ${RMWCONF}/rmwrc << "EOF"
#
# Use verbosity even if it's not passed on the command line
# 0 or 1 to disable/enable
verbosity=1
EOF
verbosity=1
fi

if [ $verbosity = 1 ]; then
	mvargs=$mvargs" -v"
fi


if [ ! $showver ]; then
cat >> ${RMWCONF}/rmwrc << "EOF"
#
# Display version at runtime, 0 or 1 to disable/enable
showver=1
EOF
showver=1
fi


if [ $showver = 1 ]; then
	displayver
fi

if [ ! $useKDETrash ]; then
echo ":"
echo ":Adding KDE Trash variables to ${RMWCONF}/rmwrc"
echo ":"
cat >> ${RMWCONF}/rmwrc << "EOF"
#
# Use KDE Trash, 0 or 1 to disable/enable
useKDETrash=0
# Using the KDE Trash folder won't work unless the
# path below is correct. Only enable it above if you
# know for sure that it's correct.
KDETrashFolder="$HOME/.local/share/Trash"
# KDE has a trashrc file that says if the trash is empty
# or not. This may be different on some systems.
KDEtrashrc="$HOME/.kde/share/config/trashrc"
EOF
useKDETrash=0
fi

if [[ ! $KDETrashFolder && $useKDETrash = 1 ]]; then
	echo "!"
	echo "! No KDE Trash Folder specified"
	echo "!"
else
	if [ $useKDETrash = 1 ]; then
		LinkWASTE=$WASTE
		WASTE=$KDETrashFolder/files
	fi
fi

if [ ! $num_undofiles ]; then
cat >> ${RMWCONF}/rmwrc << "EOF"
# Number of undo files to keep
num_undofiles=20
EOF
num_undofiles=20
fi


if [ -e ${RMWCONF}/UndoFilesCounter ]; then
	
	undofile_count=`cat ${RMWCONF}/UndoFilesCounter`
	
	else

	echo 0 > ${RMWCONF}/UndoFilesCounter
	undofile_count=1
	
	fi

if [ $undofile_count -gt $num_undofiles ]; then

	undofile_count=1

	else
	
	((undofile_count++))

fi

echo $undofile_count > ${RMWCONF}/UndoFilesCounter


UNDO_FILE=${RMWCONF}/undofile-${undofile_count}

# BUG - The statement below will overwrite an UNDO file even if rmw
# is being executed without filenames to ReMove
#

if [ $useKDETrash = 0 ]; then
	echo "" > $UNDO_FILE
fi


# The mv command has a --suffix option, but I chose to
# prepend the time and date. That keeps the file extension
# intact, and thus, if desired later, more easily opened 
# using a file manager
#
# date --help for more details
#
PREPENDSTR=`date +%Fh%Hm%Ms%S`

	for FILE in "${@}" ; do

	if [ -e "${FILE}" ]; then
		filecounter=1

# -h tests whether or not the file is a symlink.
# See ChangeLog (May 25, 2009) for more details.
# readlink will ReMove the source file, so if the 
# file is a symlink, the readlink/abs path section
# will be skipped.

# remove trailing slash otherwise -h test will fail
FILE=${FILE%/}

		if [ ! -h "${FILE}" ]; then

# readlink finds the absolute path of the file being reMoved.
# I use the absolute path (instead of present working directory)
# so we'll know where the file was originally located.
		ABSFILEPATH=`readlink -f "${FILE}"`
		ABSPATH=$(dirname "${ABSFILEPATH}")
		DEST=${WASTE}${ABSPATH}
		BNAME=`basename "${ABSFILEPATH}"`

# I should probably change the $DEST var to $DESTDIR
		if [[ ! -d "${DEST}" && $useKDETrash = 0 ]]; then
			mkdir -vp "${DEST}"
		fi

# The three lines below write to an undo file
#

if [ $useKDETrash = 0 ]; then

	echo "if [ ! -d \"${ABSPATH}\" ]; then" >> ${UNDO_FILE}
	echo "mkdir -vp \"${ABSPATH}\"" >> ${UNDO_FILE}
	echo "fi" >> ${UNDO_FILE}
fi


			if [ ! -e "${DEST}"/"${BNAME}" ]; then

if [ $useKDETrash = 1 ]; then
	mv $mvargs "${ABSFILEPATH}" "${WASTE}/${BNAME}"
	echo "[Trash Info]" > $KDETrashFolder/info/"${BNAME}".trashinfo
	echo "Path=${ABSFILEPATH}" >> $KDETrashFolder/info/"${BNAME}".trashinfo
	echo "DeletionDate=`date +%FT%T`" >> $KDETrashFolder/info/"${BNAME}".trashinfo
	
	# Tell KDE that the Trash isn't Empty
echo "[Status]" > $KDEtrashrc
echo "Empty=false" >> $KDEtrashrc
	
else
				mv $mvargs "${ABSFILEPATH}" "${DEST}"/"${BNAME}"

				echo mv $mvargs \""${DEST}"/"${BNAME}"\" \""${ABSFILEPATH}"\" >> $UNDO_FILE
fi

			else
				mv $mvargs "${ABSFILEPATH}" "${DEST}"/"${PREPENDSTR}"_"${BNAME}"
				echo mv $mvargs \""${DEST}"/"${PREPENDSTR}"_"${BNAME}"\" \""${ABSFILEPATH}"\" >> $UNDO_FILE

			fi

# 'if' statement commented, I don't think it's necessary
# anymore.
#
#		if [ ! -n "$mvargs" ]; then
			echo "ReMoved ${FILE}"
#		fi

# This is what happens to symlinks

# Removal of symlinks are not yet added to the undo file
		else
			mkdir -pv "${LinkWASTE}""${PWD}"
			mv -iv "${FILE}" "${LinkWASTE}""${PWD}"

		fi


	fi
	


	done

if [ ! -e ${RMWCONF}/timesrun ]; then
	echo 1 > ${RMWCONF}/timesrun
fi


if [ $showdu -ne 0 ];then

	timesrun=`cat ${RMWCONF}/timesrun`

	if [[ $timesrun -ge $showdu ]];
		then echo 1 > ${RMWCONF}/timesrun
		echo ""
		echo "Disk usage for Waste folder:"
		du -sh $WASTE

		elif [ $showdu -gt 0 ];then

		((timesrun++))
		echo $timesrun > ${RMWCONF}/timesrun
	fi 
fi


# Can we figure out how to empty the Waste automatically 
# if directory usage exceeds x number of bytes?
#
#echo !`du -s $WASTE`!
#if [ `du -s $WASTE` gt 64000 ]; then
#	echo "Deleting Waste"
#echo "greater than 64000"
#	/bin/rm -ir $WASTE
#fi

echo ""

# If any files were ReMoved, copy the Undo file to undofile-last
# for use with the --undo-last option
# If we didn't ReMove any files, this would copy an old undo file
# to undofile-last, some of those files may not exist anymore, or we
# we wouldn't want them restored.
# Using the filecounter var to make sure that doesn't happen
#


if [[ -e $UNDO_FILE && $filecounter && $useKDETrash = 0 ]]; then
	if [ $verbosity = 1 ]; then	
		cp -v --remove-destination $UNDO_FILE ${RMWCONF}/undofile-last
	else
		cp --remove-destination $UNDO_FILE ${RMWCONF}/undofile-last
	fi
	echo ""
	
		else

if [ ! $filecounter ]; then
	echo "Nothing to do."
	echo ""
fi

fi


exit 0


# end script
