#!/usr/bin/perl

################################################
# create md5sum for all files in subdirectories
# if mtime of MD5SUM file is less than mtime
# of any file in subdir
#
# Autor: pribyl@czilla.cz, Adam Pribyl, CZilla
# Version: 2
################################################


############### MAIN ###########################

&cdcrt;

exit;


############### SUBS ###########################

sub cdcrt {

# for each subdir we need new
    my $m5mtime;
    my $fmtime;

    my @ls = `ls`;

# if not exist MD5SUM and in directory is any file or dir create MD5SUM file
    if ((! -e "MD5SUM") and ( $#ls >= 0 )) {
	foreach $f (@ls) {
	    chomp $f;
	    if (!-d $f) {
		print "DEBUG: Creating new MD5SUM due $f\n";
		open (MD5SUM,">MD5SUM") || die "crtmd5s: Can not open MD5SUM for write";
		close MD5SUM;
		last;
	    }
	}
	$m5mtime = 0;
    } else {
	($m5atime, $m5mtime) = (stat('MD5SUM'))[8,9];
    }

    foreach $f (@ls) {
	chomp $f;
	if ($f =~ /MD5SUM/) { next };
	if (-d $f) {
	    chdir $f;
	    print "DEBUG: now in $f\n";
	    &cdcrt;
	} else {
	    ($fatime, $fmtime) = (stat($f))[8,9];
	    # if mtime of file is > than mtime of MD5SUM when we entered dir then update md5sum
	    if ($fmtime > $m5mtime ) {
		my @md5 = `cat MD5SUM`;
		# " $f$" makes sure that $f is at the end of line
		if (grep(/ $f$/, @md5) == 1) {
		    # stupid but most easy way to remove old md5sum from MD5SUM
		    open(MD5SUM,"MD5SUM") || die "crtmd5s: Can not open MD5SUM for read";
		    open(MD5SUMt,">MD5SUM.tmp") || die "crtmd5s: Can not open MD5SUM.tmp for write";

		    while (<MD5SUM>) {
			if ($_ !~ / $f$/) { 
			    print MD5SUMt "$_";
			} else {
			    print "DEBUG: Removing $f from MD5SUM\n";
			}
		    }
		    close MD5SUM;
		    close MD5SUMt;

		    open(MD5SUM,">MD5SUM") || die "crtmd5s: Can not open MD5SUM for write";
		    open(MD5SUMt,"MD5SUM.tmp") || die "crtmd5s: Can not open MD5SUM.tmp for read";

		    while (<MD5SUMt>) { print MD5SUM $_}
		    close MD5SUM;
		    close MD5SUMt;
		    unlink "MD5SUM.tmp";
		}
		print "DEBUG: Counting MD5SUM for $f\n";
		system("md5sum $f >> MD5SUM");
	    }
	}
    }
    chdir "..";
}