#!/usr/bin/env python
# -*- coding: iso-8859-1 -*-
#******************************************************************************\
#* Copyright (C) 2003-2004 Martin Blais <blais@furius.ca>
#*
#* 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., 675 Mass Ave, Cambridge, MA 02139, USA.
#*
#*****************************************************************************/

"""find-rm [<options>] <dir> [<glob/regexp> ...]

Find files under given current directory, lists them, ask for confirmation and
then delete them if confirmed.  If no globbing or regexp pattern is specified,
defaults to all files under the directory.

"""

# Note: the algorithm is lame, we should use Python code to do everything
# instead of delegating to subcommands; this has just been translated from a
# shell script.

__version__ = "Revision: 1.7 "
__author__ = "Martin Blais <blais@furius.ca>"


import sys, os
import optparse
import commands


def main():
    import optparse
    parser = optparse.OptionParser(__doc__.strip(), version=__version__[1:-1])
    parser.add_option('-x', '--no-confirm', action='store_true',
                      help="don't ask for confirmation (dangerous!)")
    parser.add_option('-i', '--case-insensitive', action='store_true',
                      help="case insensitive patterns")
    parser.add_option('-r', '--regex', action='store_true',
                      help="use regexp instead of globbing patterns")
    global opts
    opts, args = parser.parse_args()

    if not len(args):
        parser.print_help()
        raise SystemExit('Error: please specify directory to search.')

    root = args[0]

    ci = ''
    if opts.case_insensitive:
        ci = 'i'

    conditions = ['find "%s"' % root]
    for pat in args[1:]:
        if opts.regex:
            conditions.append('-%sregex' % ci)
        else:
            conditions.append('-%sname' % ci)
        conditions.append('"%s"' % pat)

    cmd = ' '.join(conditions + ['-ls'])
    s, out = commands.getstatusoutput(cmd)
    if s != 0:
        raise SystemExit('Error: running "%s"' % cmd)
    if not out:
        return
    
    print out
    print '--- Delete these files?'
    res = sys.stdin.readline().strip().lower()
    if not res: res = 'n'
    if not res in ['y', 'yes']:
        print 'Not deleting files. Exiting.'
        return 0
    
    cmd = ' '.join(conditions + ['-exec', 'rm -f {} \;', '-print'])
    os.system(cmd)
    
if __name__ == '__main__':
    main()
