#!/usr/bin/zsh

CASILEDIR=$(cd "$(dirname $0)/../" && pwd)

source ${CASILEDIR}/lib/functions.zsh

function gitcommits () {
	alias git="${GIT:-/usr/bin/git}"
	git rev-list --no-merges --reverse HEAD
}

function gitmodified () {
	alias awk="${AWK:-gawk}"
	alias git="${GIT:-/usr/bin/git}"
	alias grep="${GREP:-/usr/bin/grep}"
	git diff-tree --root --no-commit-id -r $@ |
		grep -E '100755|100644|100664' |
		awk '{print $6}' |
		grep -vE '^\.|makefile'
}

function gitadded () {
	alias git="${GIT:-/usr/bin/git}"
	git diff --word-diff-regex=. $@ | addedchars | countchars
}

function gitremoved () {
	alias git="${GIT:-/usr/bin/git}"
	git diff --word-diff-regex=. $@ | removedchars | countchars
}

function addedchars () {
	alias perl="${PERL:-/usr/bin/perl}"
	perl -ne 'print $1 while /((?<=\{\+).+?(?=\+\}))/g'
}

function removedchars () {
	alias perl="${PERL:-/usr/bin/perl}"
	perl -ne 'print $1 while /((?<=\[\-).+?(?=\-\]))/g'
}

function gitattr () {
	alias git="${GIT:-/usr/bin/git}"
	git log --no-walk --format=$@
}

function gitparent () {
	alias git="${GIT:-/usr/bin/git}"
	git rev-parse --revs-only $1^ | read newparent
	test -z $newparent && echo 4b825dc642cb6eb9a060e54bf8d69288fbee4904 || echo $newparent
}

gitcommits |
	while read sha; do
		gitattr "%h %cI %aN" $sha | read short date author
		gitparent $sha | read parent
		gitmodified $sha |
			while read file; do
				gitadded ${parent}..$sha -- $file | read added
				gitremoved ${parent}..$sha -- $file | read removed
				test $(($added-$removed)) -eq 0 && continue
				echo "INSERT INTO commits VALUES ('$short', '$author', '$date', '$file', '$added', '$removed');"
			done
	done
