#!/bin/perl
################################################################################
#
# Parse stdin looking for lines of the form (.*)$Id: (.*) $(.*).
# For the first such line found in the first 10 lines of the file,
# replace the line with:
#     $1$Id: <path> <date> <user> $$3
# The result is sent to stdout.
#
# usage: set-id.pl path < source > dest 
#
################################################################################
use strict;

my $file_name = shift @ARGV;
$file_name =~ s/^\s+//;
$file_name =~ s/\s+$//;
die "usage: $0 file_name < source_file"
    unless length ($file_name);

my $i = 0;
my $id_found;

my $user_name = $ENV{USERNAME} || $ENV{USER} || '<unknown>';

while (defined (my $line = readline (STDIN))) {
    unless ($i++ < 10 || $id_found) {
        print $line;
        next;
    }

    my $j = -1; my $k = -1;
    if (($j = index ($line, '$Id$')) >= 0) {
        $k = $j + 3;
    }
    elsif (($j = index ($line, '$Id: ')) >= 0) {
        $k = rindex ($line, '$');
    }

    if ($j >= 0 && $k > $j) {
        $id_found = 1;
        my $start = substr ($line, 0, $j);
        my $end   = substr ($line, $k);
        my ($sec,$min,$hour,$mday,$mon,$year) = localtime;
        print $start, '$Id: ', $file_name, ' ',
            sprintf ('%04d/%02d/%02d %02d:%02d:%02d', $year+1900, $mon+1, $mday, $hour, $min, $sec), 
            ' ', $user_name, ' ', $end;
    }

    else {
        print $line;
    }
}

exit 0;

