#! /bin/bash -e
# copyright parsing script from jarentaq (GitHub: jarentaq)

set -o pipefail

log() {
	git log --date=format:%Y --format='%ad %aN <%ae>'
}

process() {
	sort | uniq | awk '
    BEGIN {
        NAUTHORS=0;
        MIN_YEAR=2025
        MAP["Andrew Zonenberg <azonenberg@drawersteak.com>"] = "Andrew D. Zonenberg <azonenberg@drawersteak.com>"
        MAP["bvernoux <bvernoux@gmail.com>"] = "Benjamin Vernoux <bvernoux@gmail.com>"
    }
    {
        YEAR=$1;
        if (YEAR < MIN_YEAR) {
            MIN_YEAR=YEAR
        };
        $1="";
        AUTHOR=substr($0,2);
        if (MAP[AUTHOR]) {
            AUTHOR=MAP[AUTHOR];
        }
        if (!ALL_AUTHORS[AUTHOR]) {
            AUTHORS[NAUTHORS]=AUTHOR;
            NAUTHORS=NAUTHORS+1;
            ALL_AUTHORS[AUTHOR]=1
        }
        AUTHOR_YEAR[AUTHOR"_"YEAR] = 1
    }
    END {
        for (i=0;i<NAUTHORS;i++) {
            LAST_YEAR=0;
            printf(" ");
            USE_DASH=0;
            for (y=MIN_YEAR;y<=2025;y++) {
                if (AUTHOR_YEAR[AUTHORS[i]"_"y]) {
                    if (LAST_YEAR) {
                        if (LAST_YEAR + 1 == y) {
                            USE_DASH=1;
                        } else {
                            if (USE_DASH) {
                                printf("-%d,%d", LAST_YEAR, y);
                            } else {
                                printf(",%d", y);
                            }
                            USE_DASH=0;
                        }
                    } else {
                        printf("%d", y);
                    }
                    LAST_YEAR=y;
                }
            }
            if (USE_DASH) {
                printf("-%d", LAST_YEAR);
            }
            printf(" %s\n", AUTHORS[i]);
        }
    }'
}

iterate() {
	for i in "$@"
	do
		pushd >/dev/null 2>&1 "$i"
		log
		popd >/dev/null 2>&1
	done
}

if [ $# -eq 0 ]
then
	log | process
else
	iterate "$@" | process
fi
