#!/bin/sh

# Fill in the reviewed tag in the given file(s).
# There are 4 cases:
# 1. If the reviewed tag is already set, nothing is done and the message
#    "Reviewer and date already set in <file>" is written.
#    The reviewed tag is already set if the date part of the tag starts with
#    a numeric character.
# 2. If the reviewed tag is present but not set, the given reviewer name and
#    date are filled in (and replace possible old values).
#    The message "Set reviewer and date in <file>" is written.
# 3. If there is no reviewed tag present, it will be created after the summary
#    tag. The given reviewer name and date will be filled in.
#    The message "Added reviewed tag to <file>" is written.
# 4. If neither summary nor reviewed tag is present, nothing is done and the
#    message "Warning: no reviewed tag added or found in <file>" is written.
#    
# Run as:
#     fillreviewtag reviewer date files
#
#       reviewer     name of reviewer
#       date         date review was done as yyyy/mm/dd
#
# For example:
#     fillreviewtag "Ger van Diepen" 2004/08/20 `find . -name "*.h"`

  rev="$1"
  shift
  dat="$1"
  shift
  if [ "$1" = "" ]; then
    echo "No files found; use as 'fillreviewtag reviewer date files'"
    exit 1
  fi

  for FIL in $*
  do
    # Check if the file contains a reviewed tag.
    grep '<reviewed' $FIL > /dev/null 2>&1
    if [ $? = 0 ]; then
      # Only change reviewed tag if not filled in already.
      egrep '<reviewed.+date="[0-9].+"' $FIL >/dev/null 2>&1
      if [ $? != 0 ]; then
        sed $FIL -e 's%\(reviewed.\+date="\)[^"]*"%\1'"$dat"'"%' \
                 -e 's%\(reviewed.\+reviewer="\)[^"]*"%\1'"$rev"'"%' > $FIL.new
        echo "Set reviewer and date in $FIL"
      else
        echo "Reviewer and date already set in $FIL"
        continue
      fi
    else
      # There seems to be no reviewed tag.
      # Try to find summary tags and use them to add a reviewed tag
      # at the correct place.
      grep '</summary>' $FIL > /dev/null 2>&1
      if [ $? = 0 ]; then
        sed $FIL -e 's%</summary>%</summary>\
// <reviewed reviewer="'"$rev"'" date="'"$dat"'" tests="" demos="">\
// </reviewed>%' > $FIL.new
        echo "Added reviewed tag to $FIL";
      else
        echo "Warning: no reviewed tag added or found in $FIL";
	continue
      fi
    fi
    # Check if the file has not changed except for the reviewed tags
    grep -v '<reviewed' $FIL | grep -v '</reviewed' > a1
    grep -v '<reviewed' $FIL.new | grep -v '</reviewed' > a2
    diff a1 a2 > /dev/null 2>&1
    if [ $? != 0 ]; then
      echo "Warning: it looks as if fillreviewtag on file $FIL failed"
    else
      mv $FIL.new $FIL
    fi
    \rm -f a1 a2 $FIL.new
  done
