#!/usr/bin/env python

"""Apply regex substitution to all files on the command line or stdin."""

import sys, re, getopt

__progname__ = "re_filter.py"
__author__ = "Christopher Arndt <chris.arndt@web.de>
__version__ = "1.0"
__date__ = "03.08.2002"

__usage__ = """Usage: %(__progname__)s [-i] [-e] expr file...
Version: %(__version__)s
%(__doc__)s

-i  inline substitution
"""

def usage(d = vars()):
    sys.stderr.write(__usage__ % d)

def do_file(file):
    
    if type(file) == type(''):
       infp = open(file)
        
    if inline:
        import tempfile, os
        tempfile.tempdir = os.environ.get('TMPDIR', '/tmp')
        outfn = tempfile.mktemp()
        outfp = open(outfn, 'w')
    else:
        outfp = sys.stdout
    
    t = infp.read()
    if infp is not sys.stdin:
        infp.close()
    
    substotal = 0
    for i in range(len(regex)):
        t, subs = re.subn(regex[i][0], regex[i][1], t)
        substotal += subs

    outfp.write(t)
    if outfp is not sys.stdout:
        outfp.close()

    if inline:
        if substotal>0:
            os.system('mv -f "%s" "%s"' % (outfn, infp.name))
        else:
            os.remove(outfn)
    
    return substotal

if __name__ == '__main__':
    
    regex = []; inline = 0

    try:
        opts, args = getopt.getopt(sys.argv[1:], 'hie:', 
          ['regex='])
    except getopt.error, msg:
        usage()
        sys.exit(1)    
    
    for o,a in opts:
        if o in ['-e', '--regex']:
            regex.append(a)
        elif o == '-i':
            inline = 1
        elif o == 'h':
            usage()
            sys.exit(0)

    if not regex:
        try:
            regex = [args.pop(0)]
        except:
            usage()
            sys.exit(1) 
    
    for i in range(len(regex)):
        if regex[i][:1] == 's':
            try:
                regex[i] = regex[i][1:].split(regex[i][1], 3)[1:3]
                regex[i][0] = re.compile(regex[i][0])
            except:
                sys.stderr.write("Could not parse expression!")
                sys.exit(1)

    if not args:
        inline = 0
        args[0] = sys.stdin
    substotal = 0; sub = 0; files = 0
    for file in args:
        sub = do_file(file)
        if sub > 0:
            files += 1
        substotal += sub

    print "Made %i substitution(s) total in %i file(s)." % (substotal, files)