#! /usr/bin/env python
# -*- python -*-

####################################################################################################
# 
# PySpice - A Spice package for Python
# Copyright (C) 2014 Salvaire Fabrice
#
# 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/>. 
# 
####################################################################################################

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

import os
import re
import subprocess
import sys

from optparse import OptionParser

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

default_excluded_extension = ','.join(('~',
                                       '#',
                                       '.diff',
                                       '.pdf',
                                       '.pyc',
                                       '.tex',
                                       '.xml',
                                       '.txt',
                                       ))

default_exclusion_pattern = '\.bzr'

####################################################################################################
#
# Options
#

usage = 'usage: %prog [options]'

parser = OptionParser(usage)

parser.add_option('--root-tree-path',
                   dest='root_tree_path',
                   type='string', default='.',
                   help='root path')

parser.add_option('--exclude',
                   dest='exclusion_pattern',
                   type='string', default=default_exclusion_pattern,
                   help='exclusion regexp [%s]' % (default_exclusion_pattern))

parser.add_option('--exclude-extension',
                   dest='excluded_extension',
                   type='string', default=default_excluded_extension,
                   help='exclude extension [%s]' % (default_excluded_extension))

parser.add_option('--pattern',
                   dest='pattern',
                   type='string', default=None,
                   help='pattern')

parser.add_option('--new-pattern',
                   dest='new_pattern',
                   type='string', default=None,
                   help='new pattern')

opt, args = parser.parse_args()

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

def to_absolute_path(path):

    return os.path.abspath(os.path.expanduser(path))

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

program_path = os.path.dirname(os.path.abspath(__file__))
perl_grep = os.path.join(program_path, 'perl-grep')

root_tree_path = to_absolute_path(opt.root_tree_path)

if opt.pattern is None:
    sys.exit(1)

excluded_extension = opt.excluded_extension.split(',')

if opt.exclusion_pattern is not None:
    exclude_re = re.compile(opt.exclusion_pattern)
else:
    exclude_re = None

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

def process_file(absolut_file_name):

    return_code = subprocess.call([perl_grep, opt.pattern, absolut_file_name])
    if return_code == 0:
        print absolut_file_name
        
        if opt.new_pattern is not None:
            subprocess.call(['sed',
                             '--in-place=~',
                             's/%s/%s/g' % (opt.pattern, opt.new_pattern),
                             absolut_file_name,
                             ])

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

for root, dirs, files in os.walk(root_tree_path):
    for file_name in files:

        absolut_file_name = os.path.join(root, file_name)
        
        skipped = False
        for extension in excluded_extension:
            if file_name.endswith(extension):
                # print 'Exclude for extension', extension, file_name
                skipped = True
                break

        if not skipped and exclude_re.search(absolut_file_name) is not None:
            # print 'Exclude for regexp', file_name
            skipped = True

        if not skipped:
            process_file(absolut_file_name)

sys.exit(0)

####################################################################################################
#
# End
#
####################################################################################################
