#!/bin/bash
# rmw 0.98.4.2beta - ReMove to Waste
: '
    Copyright (C) 2011  Andy Alt (andyqwerty@users.sourceforge.net)

    This program is free software: you can redistribute it and/or modify
    it under the terms of the GNU General Public License as published by
    the Free Software Foundation, either version 3 of the License, or
    (at your option) any later version.

    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 General Public License for more details.

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

# 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
#
# Change RMWCONF if you'd like to set the location of
# the rmw configuration directory

RMWCONF="$HOME/.rmw"
# Change rmargs at your own risk
#rmargs="-i"
release_date="Apr 27, 2012"
#VERSION="svn - Jul 28, 2011"
VERSION="0.98.4.2beta - $release_date"

# The values for these variables will get overwritten if different from those
# in ~/.rmw/rmwrc. Initialized here.
debug=0
clean_mode=0
prompt_on_clean=0
prompt_on_dir=0
disk_usage=0

if [[ $color -eq 1 ]]; then
  # Define some colors
  c_reset="\e[0m"
  c_gr="\e[32;1m"
  c_red="\e[31;1m"
  c_blue="\e[36;1m"
  c_yell_on_blue="\e[33;1m\e[44m"

  # Using 1 for fatal or high priority errors. That way, I can easily change
  # the color for them later if needed.
  c_1=$c_red
  c_2=$c_gr
  c_3=$c_blue
fi


# If $WASTE is set from the cmd line or by using
# an environmental variable
if [ ${WASTE} ]; then
  tempWASTE=${WASTE%/}
  unset WASTE
fi

if [ ${DesktopTrashFolder} ]; then
  tempDTF=${DesktopTrashFolder%/}
  unset DesktopTrashFolder
fi

##### Begin Functions ######
function warranty() {
separate
echo -e $c_2"THERE IS NO WARRANTY FOR THE PROGRAM, TO THE EXTENT PERMITTED BY APPLICABLE"
echo "LAW. EXCEPT WHEN OTHERWISE STATED IN WRITING THE COPYRIGHT HOLDERS AND/OR"
echo "OTHER PARTIES PROVIDE THE PROGRAM \"AS IS\" WITHOUT WARRANTY OF ANY KIND,"
echo "EITHER EXPRESSED OR IMPLIED, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED"
echo "WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE. THE"
echo "ENTIRE RISK AS TO THE QUALITY AND PERFORMANCE OF THE PROGRAM IS WITH YOU."
echo "SHOULD THE PROGRAM PROVE DEFECTIVE, YOU ASSUME THE COST OF ALL NECESSARY"
echo -e "SERVICING, REPAIR OR CORRECTION."$c_reset
separate
exit 0
}

function checkcd {
	if [ $? != 0 ]; then
	   	separate
		echo -e $c_1"Unable to change to directory $1"
		echo -e "Error on Line: $LINENO"$c_reset
                exit 2
	fi
	}

function checkmkd {
	if [ $? != 0 ]; then
		separate
        echo -e $c_1"Unable to make directory $1"
		echo -e "Error on Line: $LINENO"$c_reset
        exit 3
    fi
}

function checkmv {
        if [ $? != 0 ]; then
	        separate
                echo -e $c_1"Unable to move $1"
		echo -e "Error on Line: $LINENO"$c_reset
                exit 4
        fi
        }

function checkrm {
        if [ $? != 0 ]; then
        	separate
                echo -e $c_1"Unable to delete $1"
		echo -e "Error on Line: $LINENO"$c_reset
                exit 5
        fi
        }


########################################################################
########################################################################
displayver() {
	echo -e "\n\t]====[ ReMove to Waste $VERSION ]====[\n"
	separate
echo "     ReMove to Waste Copyright (C) 2011  Andy Alt"
echo "This program comes with ABSOLUTELY NO WARRANTY; for details type \"rmw -5\"."
echo "This is free software, and you are welcome to redistribute it"
echo "under certain conditions; see <http://www.gnu.org/licenses/gpl.html>"
echo -e "for details.\n"
}

########################################################################
########################################################################
displayhelp() {

displayver
echo "Usage: rmw [OPTION]...[FILE]..."
echo -e "Move (mv) FILE(s) to a designated Waste folder or Desktop Trash\n"

#echo "-i / interactive"
#echo "-f / force, no prompting"
echo "  -t <file(s)>    Desktop Trash will not be used"
echo "  -d <file(s)>    files will be ReMoved to Desktop Trash"
echo "  -g              select desktop trash folder from list"
echo "  -w              select console waste folder from list" 
echo "  -u              undo last ReMove"
echo "  -s              Select a file to restore; displays list"
echo "  -z <file(s)>    Restore file(s). Accepts base file name or full path"
echo "                  to Waste directory. Not for use when desktop trash"
echo "                  is enabled"
echo "  -a              generate auto-clean script"
echo "  -2              show disk usage for Waste folder"
echo "  -9              permanently delete Waste folder"
echo "  -v <file(s)>    be verbose (quiet mode needs work)"
echo "  -V              display version"
echo -e "\nExamples: rmw -z temp foobar (restore two files)"
echo "          rmw -z ~/.Waste/files/ab*"
echo "          rmw -sz ~/Alternate-Waste/files/*"
echo "                  (select waste folder, then restore files)"
echo -e "\nFor more documentation, run: man rmw\n"

exit 0
 } 

########################################################################
########################################################################
function get_yn() {
  unset answer
  while [[ $answer != Y && $answer != y && $answer != N && $answer != n ]]; do
    read -n 1 answer
  done

  case "$answer" in
  y|Y)
  unset answer;return 1
  ;;
  N|n)
  unset answer;return 0
  ;;
  esac
}
########################################################################
########################################################################

function check_dirmove() {
  unset dir_ok
  if [ -d "$1" ]; then
    echo -e "\n Are you sure you want to move"
    echo "    $FILE"
    echo " and all its contents to the recycle bin (y/n)?"
    get_yn
    if [ $? = 1 ]; then
      dir_ok="yes"
    else
      dir_ok="no"
    fi
  fi
  
  }
#######################################################################
#######################################################################

function get_device_info() {

	old_WASTE=${WASTE}

	# cycle through each waste folder, check the default $WASTE first
	for getdev in "${old_WASTE}" "${Alt_Waste[@]}"; do
		if [[ "$1" -eq $(stat -c %d "${getdev}") ]]; then
			WASTE=${getdev}
			local changed=1
			break
		fi			  
	done

	if [[ $changed -ne 1 ]]; then
		separate
		echo -e $c_2"The file you're ReMoving:$c_reset ${FILE}"
		echo "is on a filesystem different from your Waste folder."
		echo "Edit rmwrc to add a Waste directory to Alt_Waste."
		echo -e "Using default Waste folder..."$c_reset
		separate
	fi
}

#######################################################################
#######################################################################

function get_device_info_dtf() {

	old_WASTE=${DesktopTrashFolder}

	# cycle through each DTF folder, check the default $DTF first
	for getdev in "${old_WASTE}" "${Alt_DTF[@]}"; do
		if [[ "$1" -eq $(stat -c %d "${getdev}") ]]; then
			DesktopTrashFolder=${getdev}
			local changed=1
			break
		fi			  
	done

	if [[ $changed -ne 1 ]]; then
		separate
		echo -e $c_2"The file you're ReMoving:$c_reset ${FILE}"
		echo "is on a filesystem different from your Waste folder."
		echo "Edit rmwrc to add a Waste directory to Alt_DTF."
		echo -e "Using default Desktop Trash folder..."$c_reset
		separate
	fi
}

#######################################################################
#######################################################################

function make_waste() {

  if [ ! -d "$1/info" ]; then
    separate
    echo "Create directory: $1/info (y/n)?"
    get_yn
    if [[ $? -eq 1 ]]; then
      mkdir -pv "$1/info"
      checkmkd "$1/info"
      made=1
    else echo "Not creating $1/info"
    fi
  fi
  
  if [ ! -d "$1/files" ]; then
    separate
    echo "Create directory: $1/files (y/n)?"
    get_yn
    if [[ $? -eq 1 ]]; then
      mkdir -pv "$1/files"
      checkmkd "$1/files"
      made=1
      separate
    else echo "Not creating $1/files"
    fi
  fi

}

function ReMove_file {
	if [ $prompt_on_dir = 1 ]; then
		check_dirmove "$FILE"
	fi
	if [[ $dir_ok = "yes" || ! -d "$FILE" || $prompt_on_dir = 0 ]]; then
		# $1 has a value only if the file already exists in Waste folder
		local DEXT="$1"
		# if $1 has no value, file extension will be unchanged, otherwise
		# $DEXT will be appended.
		mv $mvargs "$FILE" "$WASTE/files/$FBN$DEXT"
		local RMWINFO="$WASTE/info/$FBN$DEXT.rmw"
		checkmv "$FILE"
		echo Path="\"$AP\"" > "$RMWINFO"
		echo File="\"$FBN\"" >> "$RMWINFO"
		echo "DeletionDate=$(date +%s)" >> "$RMWINFO"
		((filecounter++))
    
		if [ $filecounter -gt 1 ]; then	
			echo "$WASTE/files/$FBN$DEXT" >> "$RMWCONF/RestoreLast.dat"
		else
			# If this is the first file being ReMoved during this run
			# write the Waste folder to the top of RestoreLast.dat
			# If Waste folder is auto-changed during this run, this will not work
			# properly. Just discovered this Bug, but I assume most people will not
			# be ReMoving files on different file systems during the same run of rmw.
			echo "$WASTE" > "$RMWCONF/RestoreLast.dat"
			echo "$WASTE/files/$FBN$DEXT" >> "$RMWCONF/RestoreLast.dat"
		fi
	fi
}
####################################################################
####################################################################
function Send_To_GUI {
  if [ $prompt_on_dir = 1 ]; then
    check_dirmove "$FILE"
  fi
  if [[ $dir_ok = "yes" || ! -d $FILE || $prompt_on_dir = 0 ]]; then
    dup_test="$DesktopTrashFolder/files/$FBN"
    if [[ ! -e "$dup_test" && ! -h "$dup_test" ]]; then
      unset DEXT
    else
      local DEXT=.$DSTR
    fi
  
    local DEST="${DesktopTrashFolder}/files/${FBN}$DEXT"
    mv $mvargs "${APFN}" "$DEST"
    checkmv "$FILE to $DEST"
    ((filecounter++))
    if [ -d "${DesktopTrashFolder}/info" ]; then
      local DESTINFO="${DesktopTrashFolder}/info/${FBN}$DEXT.trashinfo"
      echo "[Trash Info]" > "$DESTINFO"
      echo "Path=${APFN}$DEXT" >> "$DESTINFO"
      echo "DeletionDate=`date +%FT%T`" >> "$DESTINFO"
    fi
	
      # Tell KDE that the Trash isn't Empty
      # Apparently not needed for users of Xfce or GNOME
    if [ -e $KDEtrashrc ]; then
      echo "[Status]" > $KDEtrashrc
      echo "Empty=false" >> $KDEtrashrc
    fi
    unset DEXT
    unset DEST
    unset DESTINFO
  fi
 }

####################################################################
####################################################################
function restorefile {
  for file in "${@}"; do 
    # if abs or rel path was used at the command line
    if [[ ! -e "$WASTE/files/$file" && ! -h "$WASTE/files/$file" ]]; then
      gfp_info "$file" 
	
    else # if only the base filename was specified at the command line
      gfp_info "$WASTE/files/$file"
    fi
	
	
    if [ -e "$WASTE/info/$FBN.rmw" ]; then
      if [[ -e "$WASTE/files/$FBN" || -h "$WASTE/files/$FBN" ]]; then
        source "$WASTE/info/$FBN.rmw"
      
    
        if [ ! -d "$Path" ]; then
          mkdir -p "$Path"
          checkmkd $Path
        fi
    
        if [[ ! -e $Path/$File && ! -h $Path/$File ]]; then
          mv -v "$WASTE/files/$FBN" "$Path/$File"
	  checkmv $WASTE/files/$FBN
          /bin/rm -f "$WASTE/info/$FBN.rmw"
	  checkrm "$WASTE/info/$FBN.rmw"
        else
         echo -e "\nA file named $File already exists in $Path"
        fi
      fi
    else
      echo -e "\n $file not found in $WASTE/files"
    fi  
  done
  
  echo ""
}

####################################################################
####################################################################
function selectrestore {
  
  here=$(pwd)
  cd "$WASTE/files"
  checkcd $WASTE/files
  if [[ $(ls -A .) ]]; then
    select file in "abort/quit" * .*; do
      if [ "$file" = "abort/quit" ]; then
        break
      elif [[ "$file" == "*" || $file == . || $file == .. ]]; then
        separate
        echo "Unable to restore \"$file\""
	separate
        break
      fi
      restorefile "$file"
      break
    done
  cd "$here"
  else
    echo -e "\n No files found to restore in $WASTE/files"
  fi
  
}

#####################################################################
#####################################################################
function do_undo {

  # Thanks to Omnio on LQ for the code to read a file into an array
  # http://www.linuxquestions.org/questions/user/omnio-327159/

  Restore="$RMWCONF/RestoreLast.dat"

  if [ ! -e "$Restore" ]; then
    echo -e "\n ^! No restore file found. You haven't ReMoved anything to the console"
    echo " ^! waste basket yet."
    exit_msg
  fi

  local index=0

  while read line ; do
    MYARRAY[$index]="$line"
    index=$(($index+1))
  done < "$Restore"
  
  WASTE="${MYARRAY[0]}"
  unset MYARRAY[0]
  restorefile "${MYARRAY[@]}"
  
  exit 0

}

#####################################################################
#####################################################################
function gfp_info() {

# Thanks to catkin for the massive improvements to this function
# http://www.linuxquestions.org/questions/user/catkin-444761/
  curdir=$(pwd -P)
  local FILE="$1"
  
  # remove trailing slash
  FILE="${FILE%/}"

  # Get the basename of the file
  local file_basename="${FILE##*/}"

  # extracts the directory component of the full path
  local DC="${FILE%$file_basename}"

  if [ "${DC}" ]; then  
    cd "${DC}"
  fi

  # Assign present working dir to $fileap; pwd returns the
  # absolute path
  local fileap=$(pwd -P)
	
  # Append base filename to absolute path
  local ap_with_basename=$fileap/$file_basename

  # Change back to directory we started in
  if [ "${DC}" ]; then
    cd "${curdir}"
  fi
#  cd "-" &>/dev/null
  
  AP="${fileap}"
  APFN="${ap_with_basename}"
  FBN="${file_basename}"

  return 0

}


#####################################################################
#####################################################################
# Configuration file creation
 
function setupconfig {
# Create config dir if it doesn't exist
if [ ! -d "$RMWCONF" ]; then
  echo ""
  mkdir -pv "$RMWCONF"
  checkmkd $RMWCONF
fi

# Create configuration file
  
echo -e "\nCreating rmw configuration file ${RMWCONF}/rmwrc"
cat > "$RMWCONF"/rmwrc << "EOF"
#
# This config file should be created when you run rmw
# the first time.

# Default console waste folder
WASTE="$HOME"/.Waste

# Select Waste folder at startup? 0 to disable, 1 to enable
# or override with rmw -t
sel_waste=0

# If file resides on a different device/filesystem, rmw will choose
# from folder in Alt_Waste and automatically change Waste folder
# This overrides -w or $sel_waste if the file is on a different device.
auto_chg_waste=0

# Specify your alternate waste folders by editing $RMWCONF/Alt_Waste.cfg
# Keep your default WASTE folder included

# read in Alt_Waste.cfg
. $RMWCONF/Alt_Waste.cfg

# If enabling Alt_Waste folders, don't forget to remove the
# pound signs, including the one in front of the ")"

# Turn cleaning mode off(0) or on(1).
# Doesn't affect running rmw with -a
clean_mode=1

# Turns off delete confirmation when deleting files and directories
# during cleaning. rmw hasn't been extensively used yet so 1 (enabled) is
# recommended. Use rmw -a (no prompting) if you'd like to autoclean
# and be able to verify that the correct files are being deleted.
prompt_on_clean=0

# After how many days should files in Waste be deleted?
# This takes effect if clean mode is on or -a is used.
# Doesn't affect Desktop Trash.
days=30

#
# 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=0

# Prompt when moving directories to console Waste or Desktop Trash?
# 0/1 to disable/enable
prompt_on_dir=0

# ReMove files to Desktop Trash (KDE, GNOME, Xfce);
# 0 or 1 to disable/enable
useDesktopTrash=0

# Using the Desktop Trash folder won't work unless the
# path below is correct. Only enable it above if you
# know for sure that it's correct.
DesktopTrashFolder="$HOME/.local/share/Trash"

# Enable Desktop Trash folder select at startup
# 0 to disable, 1 to enable
sel_dtf=0

# If sel_dtf is set to 1, or rmw is used with the -g option,
# you can select which folder to use for Desktop Trash
#Alt_DTF=(
#"$HOME/.local/share/Trash"
#"/mnt/sdb1/.Trash-$UID"
#	)

# KDE has a trashrc file that says if the trash is empty
# or not. This may be different on some systems.
# If the file doesn't exist, this will be ignored.
KDEtrashrc="$HOME/.kde/share/config/trashrc"

# rmw can output some messages in color using escape codes if enabled (1)
#color=0
# 
# If rmw -2 is run, displays disk usage (du).
du_args=sh 
EOF

echo -e "\n$RMWCONF/rmwrc created. Check to see if it suits your needs.\n"

}

function clean_time() {

  separate
  
  local WASTE="$1"
  
  echo -e $c_3"Checking for files to clean in:"
  echo -e "$WASTE"$c_reset
  
  if [[ $(ls -A "$WASTE/info") ]]; then  # fi 1
    ls -A $WASTE/info/.*.rmw &>/dev/null
	
    if [ $? = 0 ]; then
      rmw_dotfiles="$WASTE/info/.*.rmw"
    fi
    
    ls -A $WASTE/info/*.rmw &>/dev/null
    
    if [ $? = 0 ]; then
      rmw_files="$WASTE/info/*.rmw"
    fi
    autoclean_script="$RMWCONF/rmw_autoclean.sh"
    if [ $clean_mode = 2 ]; then
	  echo Creating script: $autoclean_script
      echo "#!/bin/bash" > "$autoclean_script"
      echo "expiry=$(date +%s)" >> "$autoclean_script"
      echo "((expiry=\$expiry+3600))" >> "$autoclean_script"
      echo "if [ \$expiry -le \$(date +%s) ]; then" >> "$autoclean_script"
      echo "  echo This autoclean script has expired." >> "$autoclean_script"
      echo "  exit 0" >> "$autoclean_script"
      echo "fi" >> "$autoclean_script"
    fi
    
    echo -e $c_3"Entering Cleaning mode..."$c_reset
    
    file_del=0
        
    if [ $days -gt 1 ]; then
      days_pl="days"
    else
      days_pl="day"
    fi
    
    for clean in $rmw_files $rmw_dotfiles; do
      
      source "$clean"
	
	# In most countries, there are 86400 seconds in a day
	# This date string makes it easy to do the math
	# echo days: $days
	
      if [ $debug != 1 ]; then
        ((cleancheck=DeletionDate+(86400*days)))
      else
        ((cleancheck=DeletionDate+5))
      fi
	

	#echo $DeletionDate: $DeletionDate - cleancheck: $cleancheck
	
      if [[ $(date +%s) -ge $cleancheck ]]; then # if 6
        gfp_info "$clean"      
	FBN="${FBN%.rmw}"
	
        if [ ! -d "$WASTE/files/$FBN" ]; then # if 5
	  
	  if [ $clean_mode = 1 ]; then
	    if [  $file_del = 0 ]; then
              echo "Deleting..."
            fi
	    if [ $prompt_on_clean = 1 ]; then
	      echo -e "\n %-- Do you want to permanently delete"
	      echo " %-- $WASTE/files/$FBN (y/n)?"
	      get_yn
	    fi
	    
	    if [[ $? = 1 || $prompt_on_clean = 0 ]]; then
	      echo -e "- $WASTE/files/$FBN"
	      /bin/rm -f "$WASTE/files/$FBN"
	      checkrm "$WASTE/files/$FBN"
	      echo -e "- $clean"
	      /bin/rm -f "$clean"
	      checkrm "$clean"
	      ((file_del++))
            else
	      echo -e "Not deleting $WASTE/files/$FBN"
	    fi
	  fi
	  
	  if [ $clean_mode = 2 ]; then
	    echo "Adding $WASTE/files/$FBN"
	    echo "/bin/rm -vf \"$WASTE/files/$FBN\"" >> "$autoclean_script"
	    echo "/bin/rm -vf \"$clean\"" >> "$autoclean_script"
	    ((file_del++))
	  fi
		 
	else # if [ -d "$WASTE/files/$FBN" ] ( if 5 )
	  
	  if [ $clean_mode = 1 ]; then
	    if [  $file_del = 0 ]; then
              echo "Deleting..."
            fi
	    if [ $prompt_on_clean = 1 ]; then	  
	      echo -e "\n %! Do you want to recursively, forcibly, and permanently delete"
	      echo " %! $WASTE/files/$FBN and"
	      echo " %! all its contents (y/n)?"
	      get_yn
	    fi
	    
	    if [[ $? = 1 || $prompt_on_clean = 0 ]]; then
	      echo -e "- $WASTE/files/$FBN"
	      /bin/rm -rf "$WASTE/files/$FBN"
	      checkrm "$WASTE/files/$FBN"
	      echo "- $clean"
	      /bin/rm -f "$clean"
	      checkrm "$clean"
	      ((file_del++))
	    else # if [ $? != 0 ]
	      echo -e "\n # Not deleting $WASTE/files/$FBN\n"
	    fi
	  fi
	  	 
	  if [ $clean_mode = 2 ]; then
	    echo "Adding $WASTE/files/$FBN"
	    echo "/bin/rm -vrf \"$WASTE/files/$FBN\"" >> "$autoclean_script"
	    echo "/bin/rm -vf \"$clean\"" >> "$autoclean_script"
	    ((file_del++))
	  fi
	fi # fi 5
      fi # fi 6
    done
    
    if [[ $clean_mode = 1 && $file_del = 0 ]]; then
      echo "No files ReMoved more than $days $days_pl ago; Nothing deleted."
    fi
    
    if [ $clean_mode = 2 ]; then # if 7
      
      if [ $file_del -gt 0 ]; then
        
	if [ -e $autoclean_script ]; then
          chmod -v +x "$autoclean_script"
	  echo -e "\nautoclean script is $autoclean_script"
	  echo -e "Examine it before executing it.\n"
        else
          echo -e "\n Script generation failed\n"
	  exit_msg
        fi
      
      else # if $file_del = 0
      echo "No files in $WASTE ReMoved more than"
      echo "$days $days_pl ago; Nothing added to autoclean script."
      fi
    
    fi  # fi 7
  
  else # if info dir is empty
    echo "No .rmw info files found in $WASTE"
  fi # fi 1
  return 0
}
###########################################################
write_CurDayFile() {
	 
    echo $CurDay > "$CurDayFile"
    if [[ $? -ne 0 ]]; then
      separate
      echo "Error writing $CurDayFile:"
      echo "Please check your configuration"
      separate
    fi
}
	
###################################################################
###################################################################
function exit_msg() {
	separate
	echo -e $c_3"Exiting..."$c_reset
	separate
	exit 1
}
###################################################################
###################################################################
function separate() {
	#echo "- - - - - - - - - - - - - - - - - - - - - - - - - - - - -"
  true
}
########### End Functions ##################


	#########################################
				#				#			
				#    Main () 	#           
				#				#           
	#########################################    

if [ ! -e "$RMWCONF/rmwrc" ]; then
	setupconfig
	echo "#Alt_Waste=(" > "$RMWCONF/Alt_Waste.cfg"
	echo "#\"\$WASTE\"" >> "$RMWCONF/Alt_Waste.cfg"
	echo "#\"/mnt/second/Waste/Folder\"" >> "$RMWCONF/Alt_Waste.cfg"
	echo "#)" >> "$RMWCONF/Alt_Waste.cfg"
	exit 0
else
	. "$RMWCONF/rmwrc"
fi

if [[ -r "$RMWCONF/rmwrc" && ! $du_args ]]; then
  echo -e "\nConfig file upgrade: $RMWCONF/rmwrc\n"
  . "$RMWCONF/rmwrc"
	if [[ $Alt_Waste ]]; then
		echo "Alt_Waste=(" > "$RMWCONF/Alt_Waste.cfg"
		for AW in ${Alt_Waste[@]}; do
			echo "\"$AW\"" >> "$RMWCONF/Alt_Waste.cfg"
		done
		echo ")" >> "$RMWCONF/Alt_Waste.cfg"
	else
		echo "#Alt_Waste=(" > "$RMWCONF/Alt_Waste.cfg"
		echo "#\"\$WASTE\"" >> "$RMWCONF/Alt_Waste.cfg"
		echo "#\"/mnt/second/Waste/Folder\"" >> "$RMWCONF/Alt_Waste.cfg"
		echo "#)" >> "$RMWCONF/Alt_Waste.cfg"
	fi
	
  mv -v "$RMWCONF/rmwrc" "$RMWCONF/rmwrc.$(date +%y-%j)"
  setupconfig
  exit 0
fi

# Do we have all the variables we need? Maybe, this only checks one of them.
if [ ! "$WASTE" ]; then
	echo "Configuration file problem. Delete $RMWCONF/rmwrc and rerun rmw to "
	echo "recreate it."
	exit_msg
fi

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

#if [[ $1 == "--help" ]]; then
#	displayhelp
#fi

SAVEIFS=$IFS
IFS=$(echo -en "\n\b")
ARGS=( ${@} )
arg_count=0
for ARG in ${ARGS[@]}; do
	: ' case "$ARG" in
		'--help')
			displayhelp
			unset ARGS[$arg_count]
			;;
		'--warranty')
			warranty
			unset ARGS[$arg_count]
			;;
		'--du')
			disk_usage=1
			unset ARGS[$arg_count]
			;;
		
		*)
			echo "Unrecognized option"
	esac
	'
 
 
	
if [[ $ARG == "--help" ]]; then
		displayhelp
		unset ARGS[$arg_count]		
		
	elif [[ $ARG == "--warranty" ]]; then
		warranty
		unset ARGS[$arg_count]
		
	elif [[ $ARG == "--du" ]]; then
		disk_usage=1
		unset ARGS[$arg_count]
		
	elif [[ $ARG == "--version" ]]; then
		displayver
		unset ARGS[$arg_count]
	elif [[ $ARG == "--window-prompt" ]]; then
		window_prompt=1
		unset ARGS[$arg_count]
	fi

	((arg_count++))
	
done

unset arg_count
IFS=$SAVEIFS

if [ $tempWASTE ]; then
  WASTE="$tempWASTE"
fi

if [ $tempDTF ]; then
  DesktopTrashFolder="$tempDTF"
fi

mvargs="-"

# Thanks to Vivek Gite for the IFS trick
# http://www.cyberciti.biz/tips/handling-filenames-with-spaces-in-bash.html 
SAVEIFS=$IFS
IFS=$(echo -en "\n\b")
set -- ${ARGS[@]}
IFS=$SAVEIFS
unset SAVEIFS

# Options section needs work.

while getopts ":259avtdghuVswzfrR" Option
do

case $Option in
#    i     ) mvargs=$mvargs"i";;
    v     ) mvargs=$mvargs"v";;
#    f     ) mvargs=$mvargs"f";;
    V     ) Vminus=1;displayver;;
    t   ) useConsoleWaste=1;;
    d	) useDesktopTrash=1;;
    g	) sel_dtf=1;;
    w	) sel_waste=1;;
    a	) clean_mode=2;;
    2   ) disk_usage=1;;
    5   ) warranty;;
    9	) rf_Waste=1;;
    h	) displayhelp;;
    u	) undo=1;;
    s	) let srstf=1;;
    z	) let rstf=1;;
    f   );;
    r   );;
    R   );;
    *   ) echo -e "\nUnimplemented option chosen. rmw -h for help";exit 0;;   # DEFAULT
  esac
done


shift $(($OPTIND - 1))

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

if [[ $showver -eq 1 ]]; then
  displayver
fi

if [ $tempWASTE ]; then
  sel_waste=0
  unset tempWASTE
fi

if [ $tempDTF ]; then
  sel_dtf=0
  unset tempDTF
fi

if [[ $useConsoleWaste -eq 1 && $useDesktopTrash -eq 1 ]]; then
  echo -e "\n Console Waste enabled - over-riding Desktop Trash"
  separate
  useDesktopTrash=0
fi

if [[ $sel_dtf -eq 1 && useDesktopTrash -eq 0 ]]; then
  separate
  echo "Can not select desktop trash folder if desktop trash is not enabled"
  exit_msg
fi

if [[ $sel_waste -eq 1 && $sel_dtf -eq 1 ]]; then
  echo -e "\n Don't enable console waste select and Desktop Trash select at"
  echo " the same time."
  exit_msg
fi

if [[ $sel_waste -eq 1 && useDesktopTrash -eq 1 ]]; then
	echo -e "\n Don't enable select console waste and Desktop Trash at the same time."
	exit_msg
fi
    
if [[ $undo -ne 1 && $sel_waste -eq 1 && $Alt_Waste ]]; then
	select WASTE in "abort/quit" ${Alt_Waste[@]}; do
		if [ $WASTE = "abort/quit" ]; then
			exit_msg
		fi
		break
	done
elif [[ ! $Alt_Waste && $sel_waste -eq 1 ]]; then
	echo "No Alternate Waste folders specified in configuration."
	exit_msg
fi

if [[ $rf_Waste -eq 1 && $useDesktopTrash -eq 0 ]]; then
	separate
	echo "Use rm -rf on $WASTE (y/n)?"
	get_yn
	if [[ $? -eq 1 ]]; then
		rm -vrf "$WASTE"
		checkrm "$WASTE" $LINENO
		exit 0
	fi
elif [[ $rf_Waste -eq 1 ]]; then
	echo "rmw will not delete any console waste folders while desktop"
	echo "trash is enabled."
fi


# This seems redundant, but it's only called once per program run. Each
# alternate Waste folder must be created in advcance, to prevent the
# auto_chg_waste function from having to do it.
# Default WASTE folder should be included in Alt_Waste list in rmwrc
if [[ ${Alt_Waste} && $auto_chg_waste -eq 1 ]]; then
	for create in "${Alt_Waste[@]}"; do
		make_waste "$create"
	done
fi

if [[ $made -eq 1 ]];then
  echo "Press any key to continue..."
  read -n 1
fi

if [[ $sel_dtf -eq 1 && $useDesktopTrash -eq 1 && $Alt_DTF ]]; then
	select DesktopTrashFolder in "abort/quit" ${Alt_DTF[@]}; do
		if [ $DesktopTrashFolder = "abort/quit" ]; then
			exit 0
		fi
		break
	done
	unset Alt_DTF
elif [[ ! $Alt_DTF && $sel_dtf -eq 1 && $useDesktopTrash -eq 1 ]]; then
	echo "No Alternate Desktop Trash folders specified in configuation."
	exit_msg
fi

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

if [[ $undo -eq 1 ]]; then
	if [ $useDesktopTrash = 0 ]; then
		do_undo
	else
		echo " Desktop Trash is enabled. undo only restores from console waste."
		exit_msg
	fi
fi

if [[ $srstf -eq 1 ]]; then
	selectrestore
	exit 0
fi

if [[ $rstf -eq 1 ]]; then
	restorefile "${@}"
	exit 0
fi

# This string will be appended if rmw finds a duplicate
DSTR=$(date +%H%M%S-%y%m%d)

filecounter=0

# Make directories in $WASTE
if [[ $useDesktopTrash -eq 0 ]]; then
	unset KDEtrashrc
	make_waste "$WASTE"
else
	if [ ! -d "$DesktopTrashFolder" ]; then
		echo -e "\n^! Desktop Trash Folder not found. Check your configuration file."
		echo "^! This can also happen if you've never moved a file to your Trash from"
		echo "^! your Desktop or graphic file manager. (ex. have you recently installed"
		echo "^! a new operating system?)"
		exit_msg
	fi
fi

if [[ $clean_mode -eq 2 ]]; then
	clean_time "$WASTE"
	exit 0
fi

if [[ $disk_usage -eq 1 ]]; then
    echo -e "\nCalculating disk usage (running du -$du_args)..."
	if [[ $useDesktopTrash -eq 1 ]]; then
		du -$du_args "$DesktopTrashFolder"
	else
		if [[ $Alt_Waste ]]; then
			for AW in ${Alt_Waste[@]}; do
				separate
				du -$du_args "$AW"
			done
		else
			separate
			du -$du_args "$WASTE"
		fi
	fi
fi

protected=("$WASTE" "$DesktopTrashFolder" "$RMWCONF")


for FILE in "${@}"; do
#for FILE in "${ARGS[@]}"; do
	if [[ -e "${FILE}" || -h "${FILE}" ]]; then
		unset file_device
		gfp_info "${FILE}"
    
		if [[ $auto_chg_waste -eq 1 && $useDesktopTrash -eq 0 ]]; then
			file_device=$(stat -c %d "${FILE}")
			# Changes Waste folder based on the filesystem $FILE resides on.
			get_device_info $file_device
		fi
		
		if [[ $auto_chg_waste -eq 1 && $useDesktopTrash -eq 1 ]]; then
			file_device=$(stat -c %d "${FILE}")
			# Changes Waste folder based on the filesystem $FILE resides on.
			get_device_info_dtf $file_device
		fi
    
		# Include $WASTE in case it auto-changed recently.
		for save in ${protected[@]}  "${WASTE}"; do
			strlen_save=${#save} # How many characters in $save
			# Compare $strlen_save characters of the APFN of
			# the file being processed versus protected dir ($save)
			if [ "${APFN:0:$strlen_save}" = "$save" ]; then
				separate
				echo -e $c_2"Bad idea to use rmw on files in $save"
				echo -e "$FILE not ReMoved"$c_reset
				skip_file=1
				break
			else
				skip_file=0
			fi
		done
    
		if [[ ! -w "${FILE}" && ! -h "${FILE}" ]]; then
			separate
			echo -e $c_2"$FILE not writable, not ReMoved"$c_reset
			skip_file=1
		fi

		if [[ "$FBN" != "." && "$FBN" != ".." && $skip_file = 0 ]]; then
			if [ $useDesktopTrash = 1 ]; then
				Send_To_GUI  # User defined function
			elif [[ ! -e "$WASTE/files/$FBN" && ! -h "$WASTE/files/$FBN" ]]; then
				ReMove_file
			else
				# If the file alread exists, ReMove, but append date
				ReMove_file ".$DSTR"
			fi
		fi
	else
		# The file most likely doesn't exist, but no checks on specific reasons yet.
		echo "Unable to ReMove: $FILE"
	fi
done

# Observing rules for plural forms of English words
if [[ $filecounter -ne 1 ]]; then
	file_pl="files"
else
	file_pl="file"
fi

separate
echo -e $c_yell_on_blue"  $filecounter $file_pl ReMoved  "$c_reset

# if we're using console waste, and if clean mode is enabled

if [[ $useDesktopTrash -eq 0 && $clean_mode = 1 ]];then
  CurDay=$(date +%D)
  CurDayFile="${RMWCONF}/LastDDclean.asc"
  if [ -e "$CurDayFile" ]; then
    lastDDclean=`cat "$CurDayFile"`
    if [[ $? -ne 0 ]]; then
      separate
      echo "Error reading from $CurDayFile:"
      echo "Please check your configuration"
      separate
      lastDDclean=$CurDay
    fi
  else
    # Create CurDayFile if it doesn't exist
    # Used for cleaning mode
    write_CurDayFile
    lastDDclean=$CurDay;
  fi
  
  # If CurDay is different than the date in $CurDayFile
  if [[ $lastDDclean != $CurDay ]]; then
	write_CurDayFile
   
    # And check for files ReMoved more than x days ago
    if [[ $Alt_Waste ]]; then
      for AW in ${Alt_Waste[@]}; do
        if [[ -x "$AW"/files && -x "$AW"/info ]]; then
          clean_time "$AW"
		fi
	  done
	else
	  clean_time "$WASTE"
	fi
  fi 
fi

separate	

if [[ $window_prompt ]]; then
    echo "Press any key to close window..."
    read -n 1
fi

exit 0


# end script
