#!/usr/bin/perl -w
use strict;

=head1 NAME

  convertcvshistory.pl - convert the result of a "cvs history" command into a file consistent with a local CVSROOT/history file

=head1 SYNOPSIS

  cvs history -x TAMR -a -D 200-06-01 | sort --field-separator=]  --key=3,18 | convertcvshistory.pl > /tmp/history

=head1 DESCRIPTION

This is a supporting utility to make cvstrac better support remote repositories.

=head1 IMPLEMENTATION

The local CVSROOT/history file has lines formatted like this:

    M40a56767|mdaoh|~/burstproject|burst/runtime|1.2|KJSRuntime.js

which is: recordtype hexepoch | user | workdir | reposdir | filever | filename

The result of "cvs history -x TAMR -a -D 2004-05-01" results in lines like:

    M 2004-05-15 00:42 +0000 mdaoh 1.2 AppenderBuffer.js           burst/logging                   == ~/burstproject
    M 2004-05-15 00:42 +0000 mdaoh 1.2 index.html                                                  == ~/burstproject

which is: recordtype timestamp user filever filename reposdir workdir

=head1 CAVEATS

Because "cvs history" does not report seconds (only minutes), we cannot hope to reproduce
a bitwise identical history file to that on the remote repository.

=head1 TODO

Support "T" records.

Find out what the possibilities are for the timezone value, and handle them.

=head1 AUTHOR

Copyright 2004, Mark D. Anderson, mda@discerning.com.

This is free software; you can redistribute it and/or
modify it under the same terms as Perl itself.

=cut

=cut

# use Date::Manip;

use Time::Local;

while(<>) {
    my ($recordtype, $y, $mo, $d, $h, $mi, $tzsecs, $user, $ver, $filename, $reposdir, $workdir) = ($_ =~ m/(\S) (\d+)-(\d+)-(\d+) (\d+):(\d+) (\S+) (\S+)\s+([\d\.]+)\s+(\S+)\s+(.*)\s+== (.*)/);
    if (!$workdir) {
	print STDERR "No match to line $.: $_";
	next;
    }
    
    my $epoch_secs = timegm(0,$mi,$h,$d,$mo-1,$y);
    # my $date =  ParseDate($datetime);
    # if (!$date) {
	# print STDERR "Can't parse date '$datetime' at line $.: $_";
	# next;
    # }
    # my $epoch_secs = UnixDate($date,"%s");

    if ($tzsecs ne '+0000') {
	print STDERR "sorry, have not implemented timezone parsing for '$tzsecs' at $.:$_";
    }
    my $hexdate = sprintf("%x", $epoch_secs);
    
    # $reposdir might be empty, and regardless needs trimming
    $reposdir =~ s/^\s+//;
    $reposdir =~ s/\s+$//;

    # note that $workdir might be '<remote>'
    $workdir =~ s/\s+$//;

    print "$recordtype$hexdate|$user|$workdir|$reposdir|$ver|$filename\n";
}
