#!/usr/bin/env python3
# -*-python-*-
#
# Copyright (C) 2012-2023 The ViewCVS Group. All Rights Reserved.
#
# By using this file, you agree to the terms and conditions set forth in
# the LICENSE.html file which can be found at the top level of the ViewVC
# distribution or at http://viewvc.org/license-1.html.
#
# For more information, visit http://viewvc.org/
#
# -----------------------------------------------------------------------
#
# bump-copyright-years: internal tool for bumping copyright years
#
# -----------------------------------------------------------------------
#
import sys
import os
import time
import re

_copyright_re = re.compile(r"Copyright (\(C\)|&copy;) ([0-9]{4}-)?([0-9]{4}) " r"The ViewCVS Group")


def replace_end_year(path, year):
    try:
        lines = open(path, "r").readlines()
    except Exception:
        sys.stderr.write("WARNING: Unable to parse file as text: %s\n" % (path))
        return
    for i in range(len(lines)):
        line = lines[i]
        m = _copyright_re.search(line)
        if not m:
            continue
        if m.group(2):
            lines[i] = line[: m.start(3)] + year + line[m.end(3) :]
            open(path, "w").write("".join(lines))
            break
        elif m.group(3) != year:
            lines[i] = line[: m.end(3)] + "-" + year + line[m.end(3) :]
            open(path, "w").write("".join(lines))
            break


def bump_years_recursive(target_dir, year):
    children = os.listdir(target_dir)
    for child in children:
        if child in [".git", ".svn"]:
            continue
        child_path = os.path.join(target_dir, child)
        if os.path.isfile(child_path):
            try:
                replace_end_year(child_path, year)
            except Exception:
                sys.stderr.write("ERROR bumping copyright in file: %s\n" % (child_path))
                raise
        elif os.path.isdir(child_path):
            bump_years_recursive(child_path, year)


def bump_years(target_dir):
    year = time.strftime("%Y")
    bump_years_recursive(target_dir, year)
    sys.stdout.write("Copyright years bumped.\n\n")


if __name__ == "__main__":
    try:
        target_dir = sys.argv[1]
    except Exception:
        sys.stderr.write(
            """\
Usage: bump-copyright-years VIEWVC_DIRECTORY

Recursively update the copyright years associated with files carrying
'The ViewCVS Group' copyright in and under VIEWVC_DIRECTORY to include
the current year.
"""
        )
        sys.exit(1)
    bump_years(target_dir)
