#!/usr/bin/env bash
# reset environment variables that could interfere with normal usage
unset GREP_OPTIONS
# put all utility functions here

# make a temporary file
git_extra_mktemp() {
    mktemp -t "$(basename "$0")".XXX
}

#
# check whether current directory is inside a git repository
#

is_git_repo() {
  git rev-parse --show-toplevel > /dev/null 2>&1
  result=$?
  if test $result != 0; then
    >&2 echo 'Not a git repo!'
    exit $result
  fi
}

is_git_repo

LIST=false
FILE=""
EDITOR=$(git var GIT_EDITOR)

if test "$1" = "-l" || test "$1" = "--list"; then
  LIST=true
else
  FILE=$1
  if test "$FILE" = ""; then
    FILE=`ls | egrep 'authors|contributors' -i|head -n1`
    if test "$FILE" = ""; then
      FILE='AUTHORS'
    fi
  fi
fi

#
# list authors sorted by number of commits (descending).
#

authors() {
  git shortlog -sne | awk '{$1=""; sub(" ", ""); print}' | awk -F'<' '!x[$1]++' | awk -F'<' '!x[$2]++'
}

#
# authors.
#

if $LIST; then
  echo "$(authors)"
else
  authors >> $FILE
  test -n "$EDITOR" && $EDITOR $FILE
fi
