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

####################################################################################################
# 
# LaptopControlPanel - A Laptop Control Panel
# Copyright (C) 2014 Fabrice Salvaire
#
# 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 argparse
import os
import re
import subprocess
import sys

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

program_path = os.path.dirname(os.path.abspath(__file__))

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

# Fixme: exclude -> include ?
default_excluded_extension = ','.join(('~',
                                       '#',
                                       '.diff',
                                       '.pdf',
                                       '.pyc',
                                       '.tex',
                                       '.xml',
                                       '.txt',
                                       ))

default_exclusion_pattern = '(\.bzr|\.git)'

source_path = os.path.dirname(program_path)

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

argument_parser = argparse.ArgumentParser(description='Replace patten')

argument_parser.add_argument('--source-path',
                             default=source_path,
                             help='root path')

argument_parser.add_argument('--exclude',
                             dest='exclusion_pattern',
                             default=default_exclusion_pattern,
                             help='exclusion regexp [%s]' % (default_exclusion_pattern))

argument_parser.add_argument('--exclude-extension',
                             dest='excluded_extension',
                             default=default_excluded_extension,
                             help='exclude extension [%s]' % (default_excluded_extension))

argument_parser.add_argument('pattern', metavar='Pattern',
                             help='pattern')

argument_parser.add_argument('new_pattern', metavar='NewPattern',
                             nargs='?',
                             help='new pattern')

args = argument_parser.parse_args()

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

def to_absolute_path(path):
    return os.path.abspath(os.path.expanduser(path))

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

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

source_path = to_absolute_path(args.source_path)
print 'Source path:', source_path, '\n'

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

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

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

def is_excluded(file_name):

    for extension in excluded_extension:
        if file_name.endswith(extension):
            return True
    else:
        return exclude_re.search(absolut_file_name) is not None

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

def process_file(absolut_file_name):

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

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

for path, directories, files in os.walk(source_path):
    for file_name in files:
        absolut_file_name = os.path.join(path, file_name)
        if not is_excluded(absolut_file_name):
            process_file(absolut_file_name)

sys.exit(0)

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