#!/usr/bin/python

import os
import sys
import subprocess 
from optparse import OptionParser

USAGE = """%prog [args] pattern
Search for a pattern recursively inside files in the current folder 
ignoring development redundancies (svn, links, etc.)"""

VERSION = '0.3'

DEFAULT_EXCLUDE = ['.svn/', 'develop-link', '.egg-info']


def search(search_pattern, exclude_pattern, case_insensitive, use_colors=True):
    
    grep_args = '-RI'
    if case_insensitive:
        grep_args += 'i'

    search = ['egrep', '-n', search_pattern, grep_args, './*']
    exclude = ['egrep', '-v', exclude_pattern]
    colorize = ['egrep', '--color=auto', grep_args, search_pattern]

    cmd = ' '.join(search)  
    cmd += ' | ' + ' '.join(exclude) 
    if use_colors:
        cmd += ' | ' + ' '.join(colorize)
    
    p = subprocess.Popen(cmd, shell=True)
    try:
        sts = os.waitpid(p.pid, 0)
    except KeyboardInterrupt:
        sys.exit(-1)

def main():
    
    # TODO: Check if egrep is available

    parser = OptionParser(usage=USAGE, version=VERSION)
        
    parser.add_option('-e', '--exclude', dest='exclude',
                      action="append",
                      default=DEFAULT_EXCLUDE,
                      help=("excludes the pattern from search results. This "
                            "parameter can be used multiple times. By default "
                            "the following are already excluded: '") + \
                            "', '".join(DEFAULT_EXCLUDE) + "'"
                     )

    parser.add_option('-i', '--ignore-case', dest='case_insensitive',
                      action='store_true',
                      help='Case insentive')

    (options, args) = parser.parse_args()

    exclude_pattern = '|'.join(options.exclude)
    exclude_pattern = '"' + exclude_pattern + '"'
    
    if not len(args):
        parser.print_help()
        return
 
    search_pattern = '"' + args[0] + '"'
    
    search(search_pattern, exclude_pattern, options.case_insensitive) 

if __name__ == '__main__':
    main()
