#!/bin/perl5
# -*- perl -*-

open(FIND, "find . -type f -print |");
while (<FIND>) {
    s/[\r\n]+$//;

    next if m@/(djasm.c|stub.h)$@;

    $file = $_;
    ($dir, $base) = $file =~ /(.*)\/(.*)/;
    ($ext) = $base =~ /\.(.*)/;

    ($mode, $atime, $mtime) = (stat($file))[2,8,9];
    ($y) = (localtime($mtime))[5];
    $y += 2000 if $y < 60;
    $y += 1900 if $y < 200;

    if ($ext =~ /^(c|h|cc|y|s)$/i) {
	$cline = sprintf("/* Copyright (C) %d DJ Delorie, see COPYING.DJ for details */", $y);
    } elsif ($ext =~ /^asm$/i) {
	$cline = sprintf("; Copyright (C) %d DJ Delorie, see COPYING.DJ for details", $y);
    } elsif ($base =~ /^makefile$/i) {
	$cline = sprintf("# Copyright (C) %d DJ Delorie, see COPYING.DJ for details", $y);
    } else {
	next;
    }

    open(IN, $file);
    $found = 0;
    for ($i=0; $i<20; $i++)
    {
	$line1 = <IN>;
	$line1 =~ s/[\r\n]+$//;
	if ($line1 eq $cline) {
	    $found = 1;
	    last;
	}

	if ($line1 =~ /copyright/i && $line1 !~ /delorie/i) {
	    $found = 1;
	    last;
	}

	$found = 1 if $line1 =~ /Generated by.*DO NOT EDIT/;
    }
    close(IN);
    next if $found;

    open(IN, $file);
    $line1 = <IN>;
    $line1 =~ s/[\r\n]+$//;

    print "Update $file\n";
    print "< $line1\n";
    print "> $cline\n";
    print "\n";

    if (1) {
	open(OUT, ">$file.ctmp");
	print OUT "$cline\n";
	print OUT "$line1\n";
	print OUT while <IN>;
	close(OUT);
	close(IN);

	rename "$file.ctmp", $file;

	chmod $mode, $file;
	#utime $atime, $mtime, $file;
    }
}
