#!/bin/bash

#
# Insert last modification date at a line
# that begins with the pattern $PAT
# Default pattern is useful for html files.
# The filedate is preserved.
# Depends on the replace script
# ... online at http://www.jjj.de/
# author: Joerg Arndt ( arndt (AT) jjj.de )
# version: 2006-November-07
#

# this would be used to automatically set date as in this file:
# LASTMOD_PAT='# version:';
# LASTMOD_INS='$1';

set -

if test $# -lt 1; then
    echo "need at least one filename."
    exit 1;
fi

# which pattern to look for:
PAT='<!--LASTMOD-->';

# what to insert (followed by date):
INS='$1<BR>Last modified';

# if supplied in environment, set PAT/INS as given:
test -n "$LASTMOD_PAT"  &&  PAT=$LASTMOD_PAT
test -n "$LASTMOD_INS"  &&  INS=$LASTMOD_INS


TMPFILE=/tmp/lastmod.tmp.$$

trap "rm -f $TMPFILE 2>/dev/null" 0

type -p replace > /dev/null || { echo "Need replace.";  exit 1; }
type -p readlink > /dev/null || { echo "Need readlink.";  exit 1; }

for f in $*; do
    test -L $f && f="$(readlink $f)";
#    echo " ::f = [$f] PAT=[$PAT] INS=[$INS]";
    if test -f $f; then

        test -r  $f  ||  { echo "$f: not readable"; exit 1; }
        test -w  $f  ||  { echo "$f: not writable"; exit 1; }

        # copy to tmpfile:
        cp -p $f $TMPFILE  || { echo "cannot create temp-file ${TMPFILE}"; exit 1;  }

        # format = 2000-October-01 (22:01)
        DATE=`date -r $f +'%Y-%B-%d (%H:%M)'`; # date and time from file $f
#        DATE=`date -r $f +'%Y-%B-%d'`; # date

        # insert date:
#        echo "   ----->  FILE == $f  <-----"
#        set -vx
        replace -Qf "^ *($PAT).*\$" "$INS $DATE" $TMPFILE  ||  exit 1;
#        set -

        # restore filedate (!):
#        touch -r $f $TMPFILE
        touch -r $f $TMPFILE -d '+1 seconds' # backup-safety, but 'drift'

        # copy back:
        DIFF=$(diff $TMPFILE $f)
        if [ -n "$DIFF" ]; then # only if file changed
            echo " --- $f: "
            echo "$DIFF"
            read -p "ctrl-C to interrupt,  return to accept " a;
            cp -pv $TMPFILE $f
        fi
    else
        echo "skipping $f: not a regular file"
    fi
done

rm -f $TMPFILE

exit 0;

##################################
