#!/bin/sh

FILE=""
LIST=false
TAG="n.n.n"

while [ "$1" != "" ]; do
  case $1 in
    -l | --list )
      LIST=true
      ;;
    -t | --tag )
      TAG=$2
      shift
      ;;
    * )
      FILE=$1
      ;;
  esac
  shift
done

DATE=`date +'%Y-%m-%d'`
HEAD="\n$TAG / $DATE \n==================\n\n"

if $LIST; then
  version=$(git describe --tags --abbrev=0 $(git rev-list --tags --max-count=1))
  if test -z "$version"; then
    git log --pretty="format: * %s"
  else
    git log --pretty="format: * %s" $version..
  fi
  exit
fi

CHANGELOG=$FILE
if test "$CHANGELOG" = ""; then
  CHANGELOG=`ls | egrep 'change|history' -i`
  if test "$CHANGELOG" = ""; then
    CHANGELOG='History.md';
  fi
fi
tmp="/tmp/changelog"
printf "$HEAD" > $tmp
git-changelog --list >> $tmp
printf '\n' >> $tmp
if [ -f $CHANGELOG ]; then cat $CHANGELOG >> $tmp; fi
mv $tmp $CHANGELOG
test -n "$EDITOR" && $EDITOR $CHANGELOG
