#!/usr/bin/python
# trash: put files and dirs in the trashcan
#
# Copyright (C) 2007,2008 Andrea Francia Trivolzio(PV) Italy
#
# 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 2
# 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, write to the Free Software
# Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  
# 02110-1301, USA.

from libtrash import File
from libtrash import TrashDirectory
from libtrash import TrashedFile
from optparse import OptionParser
import optparse
import libtrash

def trash (f) :
    """ 
    Trash a file in the appropriate trash directory.
    If the file belong to the same volume of the trash home directory it will
    be trashed in the home trash directory.
    Otherwise it will be trashed in one of the relevant volume trash directories.
    
    Each volume can have two trash directories, they are 
        - $volume/.Trash/$uid
        - $volume/.Trash-$uid
    
    Firstly the software attempt to trash the file in the first directory then 
    try to trash in the second trash directory.
    """
    try: 
        volume = f.parent.volume
    
        if TrashDirectory.getHomeTrashDirectory().volume == volume :
            trashed_file = TrashDirectory.getHomeTrashDirectory().trash(f)
        else :
            if volume.hasCommonTrashDirectory() :
                trashed_file = volume.getCommonTrashDirectory().trash(f)
            else :
                trashed_file = volume.getUserTrashDirectory().trash(f)
        assert(isinstance(trashed_file, TrashedFile))
                
        if options.verbose:
            print "`%s' trashed in %s " % (arg, trashed_file.trash_directory)
    except OSError, e:
        # occour when the file cannot be moved
        print "trash: cannot trash `%s': %s" % (arg, str(e))
    except IOError, e:
        # occour when the file does not exist
        print "trash: cannot trash `%s': %s" % (arg, str(e))    

class MyOptionParser(OptionParser) :
    def __init__ (self,
                  usage=None,
                  option_list=None,
                  option_class=optparse.Option,
                  version=None,
                  conflict_handler="error",
                  description=None,
                  formatter=None,
                  add_help_option=1,
                  prog=None,
                  epilog=None):
        OptionParser.__init__(self,
                  usage,
                  option_list,
                  option_class,
                  version,
                  conflict_handler,
                  description,
                  formatter,
                  add_help_option,
                  prog)
        self.epilog=epilog

    def format_help(self, formatter=None):
        result=OptionParser.format_help(self,formatter)
        if self.epilog:
            return result + "\n" + self.epilog + "\n"
        else:
            return result

parser = MyOptionParser(usage="%prog [OPTION]... FILE...",
                      description="Put files in trash",
                      version="%%prog %s" % libtrash.version,
                      epilog=
"""To remove a file whose name starts with a `-', for example `-foo',
use one of these commands:

  trash -- -foo

  trash ./-foo
  
Report bugs to <andreafrancia@sourceforge.net>.""")

parser.add_option("-d",
                  "--directory",
                  action="store_true",
                  help="ignored (for GNU rm compatibility)")

parser.add_option("-f",
                  "--force",
                  action="store_true",
                  help="ignored (for GNU rm compatibility)")

parser.add_option("-i",
                  "--interactive",
                  action="store_true",
                  help="ignored (for GNU rm compatibility)")

parser.add_option("-r",
                  "-R",
                  "--recursive",
                  action="store_true",
                  help="ignored (for GNU rm compatibility)")

parser.add_option("-v",
                  "--verbose",
                  action="store_true",
                  help="explain what is being done",
                  dest="verbose")

(options, args) = parser.parse_args()


if len(args) <= 0:
    parser.error("Please specify the files to trash.")


for arg in args :
    f = File(arg)
    trash(f)
