#!/bin/bash

# Generate old-style ChangeLog files from the GIT log. Ultimately we may
# wish to insert this into ChangeLog

footer=false
printdate=true
directory=.
since=
modules=true
quiet=false;
moduleoptions=

done=false
while [ $done = false ]; do
    case "$1" in
	--footer)
		footer=true
		shift
		;;
	--nodate)
		printdate=false
		shift
		moduleoptions+="--nodate"
		;;
	--quiet)
		quiet=true
		shift
		;;
	--nomodules)
		modules=false
		shift
		;;
	--dir=*)
		directory="`echo $1 | sed 's/--dir=//'`"
		shift
		modules=false
		;;
	--since=*)
		since="`echo $1 | sed 's/--since=//'`"
		shift
		;;
	*)	done=true
		;;
    esac
done

tag="$1"

if [ -z "$tag" -a -z "$since" ]; then
   echo "Usage: `basename $0` option ... [version] [path ...]"
   echo "Options:"
   echo "    --footer"
   echo "    --nodate"
   echo "    --nomodules"
   echo "    --since=<date>"
   echo "    --dir=<dir>"
   exit 1
fi

# Ensure case-sensitive matching
LANG=C

case "$tag" in
   [0-9].[0-9]*.[0-9]*)
	tag=V${tag}
	;;
esac

if [ ! -z "$since" ]; then
  opt="--since=$since"
else
  shift
  opt="$tag.."
fi

cd $directory

if [ "$quiet" = true ]; then
  git log "$opt" --pretty=format:"PATCH[%ad]%n%s%n%b" $* | grep -q '^[A-Z][A-Z]*:'
  exit $?
fi

header ()
{ hdr="$*"
  eq=`echo $hdr | sed 's/./=/g'`
  echo $eq
  echo $hdr
  echo $eq
  echo
}

(
if [ "$directory" = "." ]; then
  header "SWI-Prolog Changelog since $tag"
else
  header "Package `basename $directory`"
fi

git log "$opt" --pretty=format:"PATCH[%ad]%n%s%n%b" $* | awk '
BEGIN		{ doprint="false";
		  dateprinted="";
		}
/^PATCH[[]/	{ date="["  $2 " " $3 " " $5 "]";
		  doprint="false";
		  next;
	        }
/^[A-Z][A-Z]*:/	{ if ( dateprinted != date )
		  { if ( "'$printdate'" == "true" )
		    { printf("%s\n\n", date);
		    }
		    dateprinted = date;
		  }
		  printf(" * %s\n", $0);
		  doprint="true";
		  next;
		}
/.*/ 		{ if ( doprint == "true" )
		  { if ( $0 != "<unknown>" )
		    { printf("   %s\n", $0);
		    } else
		    { printf("\n");
		    }
		  }
		  next;
		}
' ) | fmt -ut

# Include submodules

if [ "$modules" = true ]; then
  if [ -z "$since" ]; then
    since=`git show --quiet --pretty=format:%cd "$tag^{commit}"`
  fi

  echo

  for d in `git submodule -q foreach pwd`; do
    if $0 --dir="$d" --since="$since" --quiet; then
      echo
      $0 --dir="$d" --since="$since" $moduleoptions
#   else
#     echo "Package `basename $d`: no changes"
    fi
  done
fi

if [ "$footer" = true ]; then
   echo ==============
   echo VERSION $tag
   echo ==============
fi
