#!/bin/zsh
# a wrapper around git and vi
# (c) Copyright Miek Gieben, 2009
# Licensed under GPL v3
# expands $[H]ash$ to $[H]ash: file short_hash date committer $
# block quotes are there to fool gitvi
# $Hash$

[[ ! -x =git ]] && exit 1

who=${SUDO_USER:-$LOGNAME}
full=$(getent passwd $who | awk -F: '{ gsub(/,*/, ""); print $5 }')
author="$full <$who@atoom.net>"

function search_git_dir {
    gpath="$1"

    [[ -d "$gpath/.git" ]] && echo "$gpath" && return
    [[ -z "$gpath" ]] && echo "" && return

    # strip that last path component and try again
    search_git_dir "${gpath%/*}"
}

function usage {
    cat <<-EOF
 gitvi [-h] [-m MSG] FILE [FILE]...

 use git and vi together

     -m MSG    use MSG as commit message
     -h        this help
EOF
    exit
}

zparseopts -D -K -- m:=o_msg h=o_help
[[ $? != 0 || "$o_help" != "" ]] && usage
o_msg=$o_msg[2]

for file in "$@"; do
    dir=$(dirname "$file")
    cd "$dir"
    base=$(basename "$file")

    if [[ -z $(search_git_dir "$PWD") ]]; then
	# make a new one in $PWD
	git init || exit 1
    else
	#echo FOUND ONE
    fi
    chmod +w "$base" 2> /dev/null

    if ${EDITOR:-/usr/bin/vi} "$base"; then
	[[ ! -e $base ]] && exit 0
	git add $base
	# collapse $Hash$ line
	sed -i -e 's/\$[H]ash:.*\$/$H''ash$/' "$base"
	if [[ -z "$o_msg" ]]; then
	    git commit --author "$author" "$base"
	else
	    git commit -m "$o_msg" --author "$author" "$base"
	fi
    fi

    id=$(git-show -s --pretty=format:$base\ %h\ %ci\ $who%n -- "$base") 
    [[ -z $id ]] && exit 1

    # re-add $Hash$ line
    sed -i -e 's/\$[H]ash\$'/\$H''ash:\ $id\ \$/ "$base"

    chmod a-w $base 2> /dev/null
    cd - >/dev/null
done