#!/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);
    $line1 = <IN>;
    $line1 =~ s/[\r\n]+$//;
    if ($line1 eq $cline) {
	close(IN);
	next;
    }

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

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

    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;
}
