#!/bin/bash

# Copyright (C) 2017-2017 Alexandre Cassen, <acassen@gmail.com>

NO_COPY=
UPDATED=
GIT_UPDATE=0
GIT_OVERRIDE=0
GIT_COMMIT_SUBJECT="Copyright update"
TEST_MODE=0

show_help()
{
	cat <<EOF
$0 - Usage:

	-h              Show this!
	-g		Do git update for copyright messages
	-o		Override requiring clean working tree for git update
	-t		Test mode - don't do a git commit

EOF
}

while getopts ":hgot" opt; do
	case $opt in
		h)
			show_help
			exit 0
			;;
		g)
			GIT_UPDATE=1
			;;
		o)
			GIT_OVERRIDE=1
			;;
		t)
			TEST_MODE=1
			;;
		?)
			echo Unknown option -$OPTARG && show_help && exit 1
			;;
		:)
			echo Option -$OPTARG parameter missing && exit 1
			;;
	esac
done

# We can only do a git update if either the working tree is clean or override is specified and all tracked files are added for committing
if [[ $GIT_UPDATE -eq 1 && \
      ( ( $GIT_OVERRIDE -eq 0 && -n $(git status -s | grep -Ev "^\?\? " ) ) ||
      ( $GIT_OVERRIDE -ne 0 && -n $(git status -s | grep -Ev "^\?\? " | grep -v "^M " ) ) ) ]]; then
	echo Cannot do git update if working tree not clean
	exit 1
fi

for FILE in $(git ls-tree --name-status -r HEAD); do
	[[ "configure COPYING aclocal.m4 ChangeLog ar-lib compile depcomp " =~ " ${FILE##*/} " ]] && continue

	CP=$(grep "[Cc]opyright" $FILE)
	[[ $? -ne 0 ]] && continue
	[[ ! $CP =~ [Cc]assen ]] && NO_COPY="$NO_COPY $FILE" && continue

	grep -q "[Cc]opyright .*[Cc]assen" $FILE
	[[ $? -ne 0 ]] && NO_COPY+=" $FILE" && continue

	CP=$(grep "[Cc]opyright .*[Cc]assen" $FILE | sed -e "s/.*\([Cc]opyright\)/\1/")
	[[ ! "$CP" =~ "20" ]] && NO_COPY="$NO_COPY $FILE" && continue
	[[ "$CP" =~ "2001-%s" ]] && NO_COPY="$NO_COPY $FILE" && continue

	CP_YEAR=$(<<<$CP sed -e "s/.*\(20[0-9][0-9]\)[^0-9]/\1/" -e "s/\(....\).*/\1/")

	GIT_TIMESTAMP=$(git log -1 --format=%ct $FILE)
	GIT_YEAR=$(date -d "1970-01-01 UTC ${GIT_TIMESTAMP} seconds" +"%Y")

	[[ $CP_YEAR = $GIT_YEAR ]] && continue

	COMMIT_SUBJECT=$(git log -1 --format=%s $FILE)
	[[ $COMMIT_SUBJECT = $GIT_COMMIT_SUBJECT ]] && continue

	START=$(<<<$CP sed -e "s/^\(.*\)20[0-9][0-9][^0-9].*/\1/")
	END=$(<<<$CP sed -e "s/.*20[0-9][0-9]\([^0-9]\)/\1/")

	NEW_CP=$(<<<"$START$GIT_YEAR$END" sed -e "s/@linux-vs.org/@gmail.com/")
	sed -i -e "s/$CP/$NEW_CP/" $FILE
	UPDATED+=" $FILE"
done

if [[ $GIT_UPDATE -eq 1 ]]; then
	git add $UPDATED
	[[ $TEST_MODE -eq 0 ]] && git commit -s -m "$GIT_COMMIT_SUBJECT"
fi

[[ -n $UPDATED ]] && echo Updated: $UPDATED
[[ -n $NO_COPY ]] && echo No usable copyright statements: $NO_COPY
