#!/bin/sh
#
# $Id$
# $HeadURL$
#
# alias git git_with_commiter
#

function setupAuthorCommiter() {
    # predefined users
    declare -a users=( \
        'Christian Ehrlicher' \
        'Hanna Rathje' \
        'Hannes Bäuerle' \
        'Hans-Jürgen Lampe' \
        'Iuliana Ojog' \
        'Malte Diers' \
        'Mike Wille' \
        'Norbert Thoden' \
        'Patrick Galler' \
        'Patric Karwat' \
    )

    # the users in the last 1000 commits
    committers=`git log --pretty=format:%aN -n 1000 | sort -u `

    # join arrays committers and users
    while read -r line; do
        users=("${users[@]}" "$line")
    done <<< "$committers"

    # make users unique
    IFS=$'\n' committers=($(sort -u <<<"${users[*]}"))

    # the last committer
    last_committer=`git log --pretty=format:%aN -n 1`

    # show possible users
    echo -e "\e[31mAvailable committers:\e[0m"
    defaultId=0
    for ((i=0; i < ${#committers[@]};i++)) {
        idx=$((i + 1))
        if [ "${committers[$i]}" = "$last_committer" ] ; then
            defaultId=$idx
            echo -e "\e[32m $idx - ${committers[$i]}\e[0m (default)"
        else
            echo " $idx - ${committers[$i]}"
        fi
    }
    echo " 0 - new committer"
    echo "enter a number for the committer to use or nothing for the last committer"

    # now ask for the committer to use
    while [ true ]; do
        echo -n "Please enter number [default=${defaultId}]: "
        read line < /dev/stdin
        # empty -> default
        if [ -z $line ] ; then
            line=$defaultId
        fi
        # its a digit and between the valid range
        if [ -z "${line##[0-9]*}" ] && [ "$line" -ge 0 ] && [ "$line" -le "${#committers[@]}" ]; then
            break
        fi
    done

    if [ $line -eq 0 ] ; then
        echo -n "Please enter full committer name:"
        read git_name < /dev/stdin
    else
        git_name=${committers[$((line - 1))]}
    fi

    git_email="${git_name// /.}@rheinmetall.com"
    echo "Using '$git_name ($git_email)' as author and committer"

    export GIT_AUTHOR_NAME="$git_name"
    export GIT_AUTHOR_EMAIL="$git_email"
    export GIT_COMMITTER_NAME="$git_name"
    export GIT_COMMITTER_EMAIL="$git_email"
}

if [ $# -ge 1 ] ; then
    gitopt="$1"
    case $gitopt in
        commit) setupAuthorCommiter ;;
        *);;
    esac
fi

exec git "$@"
