#!/bin/bash
###
# Check all added or modified files that have a copyright line
# for an up-to-date copyright year.
# e.g. "Copyright (C) 2018-2019 The KPhotoAlbum Development Team"
###

set -e

if [[ -z "$CHECK_COPYRIGHT_HEADER" ]]
then
	CHECK_COPYRIGHT_HEADER=$(git config --bool --get kpa.checkCopyrightHeader || echo true)
fi
if [[ "$CHECK_COPYRIGHT_HEADER" == false ]]
then
	exit 0
fi

year=$(date +%Y)
IFS=$'\n'
for line in $(git status -s)
do
	# if the file is added or modified
	if [[ $line == A* || $line == M* ]]
	then
		if head -n5 "${line:3}" | grep -q -i copyright
		then
			if ! head -n5 "${line:3}" | grep -q -i "copyright.*[ -]$year"
			then
				missing_year="$missing_year\n${line:3}"
			fi
		fi
	fi
done

if [ -n "$missing_year" ]
then
	printf "Please update copyright year for the following files:$missing_year\n"
	# also check if the Copyright statement in main.cpp is ok:
	if ! grep -q -i "i18n(\"Copyright (C) 2003-$year " main.cpp
	then
		printf "...and also update the copyright statement in main.cpp!\n"
	fi
	printf "** You can suppress this check by setting 'git config kpa.checkCopyrightHeader false'\n"
	printf "** or by setting the environment variable CHECK_COPYRIGHT_HEADER=false\n"
	exit 1
fi
