#!/usr/bin/perl -w

require 5.004;
use Time::Local;

local $line;
local $wfile;
local $bestrev;
local $bestdate;
local $rev;
local $argdate;
local $date;
local $pdate;
local %revisions;

if ($#ARGV != 0) {
	die ("One argument required");
}

if ($ARGV[0] =~ m{(....)/(..)/(..) (..):(..):(..)}) {
	$argdate = timegm($6, $5, $4, $3, $2 - 1, $1 - 1900);
} else {
	die ("Accepted format: YYYY/MM/DD HH:mm:ss");
}

open (CVSLOG, "cvs -q log |") ||
	die ("Cannot read cvs log");
while (<CVSLOG>) {
	$line = $_;
	chop $line;
	if ($line =~ /Working file: (.*)$/) {
		$wfile = $1;
		$bestrev = "0";
		$bestdate = 0;
		undef $rev;
		undef $date;
		undef $pdate;
		next;
	}
	if ($line =~ /revision (.*)$/) {
		$rev = $1;
		next;
	}
	if ($line =~ /^\============*$/) {
		if ($bestrev ne "0") {
			$revisions{"$wfile"} = $bestrev;
		} else {
			unlink $wfile;
		}
		next;
	}
	if ($line =~ /date: ([^;]*);/) {
		$date = $1;
	}
	else {
		next;
	}
	if ($date =~ m{(....)/(..)/(..) (..):(..):(..)}) {
		$pdate = timegm($6, $5, $4, $3, $2 - 1, $1 - 1900);
	}
	else {
		die ("Cannot parse date");
	}
	if ( ($pdate < $argdate) && ($pdate >= $bestdate) ) {
		$bestdate = $pdate;
		$bestrev = $rev;
	}
}

foreach (keys %revisions) {
	print "cvs -q update -r $revisions{$_} $_\n";
	system ("cvs -q update -r $revisions{$_} $_");
}
