#    Copyright 2018 Arm Limited
#
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
#
#     http://www.apache.org/licenses/LICENSE-2.0
#
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.

import argparse, os, re, datetime, subprocess, logging

def Update(file_name, file_contents, year_copyright, year_last_modified, match):
    x = file_contents.find(year_copyright)
    if match.group(1):
        modified = file_contents[0:x]+str(year_last_modified)+file_contents[x+4:]
    else:
        modified = file_contents[0:x+4]+'-'+str(year_last_modified)+file_contents[x+4:]
    with open(file_name, 'w') as file:
        file.write(modified)

def File_Check(file_name):
    _, ext = os.path.splitext(file_name)
    if ext == '.py':
        file = open(file_name, 'r')
        file_contents = file.read()
        file.close()
        match = date_regex.search(file_contents)
        if match:
            year_copyright = match.group('year')
            year_last_modified = Get_git_year(file_name)
            if int(year_last_modified) > int(year_copyright):
                logging.debug('Updated Arm copyright in: %s', file_name)
                Update(file_name, file_contents, year_copyright, year_last_modified, match)
            else:
                logging.debug('Found Arm copyright in: %s', file_name)
        elif 'Copyright' not in file_contents:
            logging.warning('No copyright found in: %s', file_name)

def Get_git_year(full_directory):
    info = subprocess.check_output('git log -n 1 '+(os.path.basename(full_directory)),
                                   shell = True, cwd = os.path.dirname(full_directory))
    info_split_lines = info.split('\n')
    info_split_words = info_split_lines[2].split()
    return info_split_words[5]

parser = argparse.ArgumentParser(description='Updates the year of the Copyright of Arm Limited python files')
parser.add_argument('directory', metavar='DIR', type=str, help='Enter a file or directory for copyright updating')
parser.add_argument('-v', '--verbose', action='store_true', help='Enable verbose output')

args = parser.parse_args()
date_regex = re.compile(r'Copyright (\d+-)?(?P<year>\d+) A(rm|RM) Limited')

log_level = logging.DEBUG if args.verbose else logging.INFO
logging.basicConfig(format='%(message)s', level=log_level)

if os.path.isfile(args.directory):
    File_Check(args.directory)
else:
    for folder, _, files in os.walk(args.directory):
        for file_name in files:
            File_Check(os.path.join(folder, file_name))