#!/usr/bin/env bash


cd "$(git root)" || { echo "Can't cd to top level directory";exit 1; }

commit=""
test $# -ne 0 && commit=$@
project=${PWD##*/}

#
# get date for the given <commit>
#

date() {
  git log --pretty='format: %ai' $1 | cut -d ' ' -f 2
}

#
# get active days for the given <commit>
#

active_days() {
  date $1 | sort -r | uniq | awk '
    { sum += 1 }
    END { print sum }
  '
}

#
# get the commit total
#

commit_count() {
  git log --oneline $commit | wc -l | tr -d ' '
}

#
# total file count
#

file_count() {
  git ls-files | wc -l | tr -d ' '
}

#
# list authors
#

format_authors() {
  # a rare unicode character is used as separator to avoid conflicting with
  # author name. However, Linux column utility will escape tab if separator
  # specified, so we do unesaping after it.
  LC_ALL=C awk '
  { args[NR] = $0; sum += $0 }
  END {
    for (i = 1; i <= NR; ++i) {
      printf "%s♪%2.1f%%\n", args[i], 100 * args[i] / sum
    }
  }
  ' | column -t -s♪ | sed "s/\\\x09/\t/g"
}

#
# fetch repository age from oldest commit
#

repository_age() {
  git log --reverse --pretty=oneline --format="%ar" | head -n 1 | LC_ALL=C sed 's/ago//'
}

#
# list the last modified author for each line
#
single_file() {
  while read data
  do
    if [[ $(file "$data") = *text* ]]; then
      git blame --line-porcelain "$data" 2>/dev/null | grep "^author\ " | LC_ALL=C sed -n 's/^author //p';
    fi
  done
}

#
# list the author for all file
#
lines() {
  git ls-files | single_file
}

#
# get the number of the lines
#
line_count() {
  lines | wc -l
}

result() {
  lines | sort | uniq -c | sort -rn | awk '
    { args[NR] = $0; sum += $0 }
    END {
      for (i = 1; i <= NR; ++i) {
        printf " %s, %2.1f%%\n", args[i], 100 * args[i] / sum
      }
    }
    ' | column -t -s,
}

# summary

echo
echo " project  : $project"

if test "$1" = "--line"; then
  echo " lines    : $(line_count)"
  echo " authors  :"
  lines | sort | uniq -c | sort -rn | format_authors
else

  echo " repo age :" $(repository_age)
  echo " active   :"  $(active_days) days
  echo " commits  :" $(commit_count)
  if test "$commit" = ""; then
    echo " files    :" $(file_count)
  fi
  echo " authors  : "
  git shortlog -n -s $commit | format_authors
fi
