#!/bin/bash

readable_interval()
{
  local sec=$1
  local min hr day wk
  if test "$sec" -lt 60; then echo "$sec seconds"; return; fi

  min=$((sec / 60)); : $((sec %= 60))
  test 30 -le $sec && : $((min++))
  if test "$min" -lt 60; then echo "$min minutes"; return; fi

  hr=$((min / 60)); : $((min %= 60))
  test 30 -le $min && : $((hr++))
  if test "$hr" -lt 24; then echo "$hr hours"; return; fi

  day=$((hr / 24)); : $((hr %= 24))
  test 12 -le $hr && : $((day++))
  if test "$day" -lt 24; then echo "$day days"; return; fi

  wk=$((day / 7)); : $((day %= 7))
  test 4 -le "$day" && : $((wk++))
  echo "$wk weeks"
  return
}

my_first_name=$(git config --global user.name|cut -d' ' -f1)
V1=$(cat .prev-version)
V0=$(git show "v$V1:.prev-version")
pkg=$(perl -nle '/^PACKAGE = (.*)/ and print $1' Makefile)

n_ci=$(git rev-list "v$V0..v$V1" | wc -l)
n_p=$(git shortlog "v$V0..v$V1" | grep -c '^[^ ]')

prev_release_date=$(git log --pretty=%ct -1 "v$V0")
this_release_date=$(git log --pretty=%ct -1 "v$V1")
n_seconds=$((this_release_date - prev_release_date))
time_since_prev=$(readable_interval "$n_seconds")
n_gl_commits=$(( -2 + $(git submodule summary "v$V0"|wc -l) ))

cat <<EOF
This is to announce $pkg-$V1, a stable release.

There have been $n_ci commits by $n_p people in the $time_since_prev since $V0.

See the NEWS below for a brief summary.

Thanks to everyone who has contributed!
The following people contributed changes to this release:

$(git shortlog "v$V0..v$V1" | perl -lne '/^(\w.*):/ and print "  ".$1')

$my_first_name [on behalf of the $pkg maintainers]
==================================================================

Here is the GNU $pkg home page:
    http://gnu.org/s/$pkg/

For a summary of changes and contributors, see:
  http://git.sv.gnu.org/gitweb/?p=$pkg.git;a=shortlog;h=v$V1
or run this command from a git-cloned $pkg directory:
  git shortlog v$V0..v$V1

To summarize the $n_gl_commits gnulib-related changes, run these commands
from a git-cloned $pkg directory:
  git checkout v$V1
  git submodule update --init
  git submodule summary v$V0
EOF
