#!/usr/bin/perl -w

#----------------------------------------------------------------------
# copyright (C) 2001 e-smith, inc.
#		
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2 of the License, or
# (at your option) any later version.
#		
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.	See the
# GNU General Public License for more details.
#		
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA 02111-1307  USA
# 
# Technical support for this program is available from e-smith, inc.
# Please visit our web site www.e-smith.com for details.
#----------------------------------------------------------------------

# Convert daemontools-0.53 cyclog log files to daemontools-0.70 multilog
# log files.

package esmith;

use strict;
use Errno;

# The new files will be owned by the qmaill user.

my $user = "qmaill";
my (undef, undef, $uid, $gid) = getpwnam($user);

chdir "/var/log/qmail";

if (opendir DOT, ".")
{
    foreach (readdir DOT)
    {
	# cyclog files begin with an @ and are followed by the epoch
	# time as a zero prefixed 14 digit decimal integer.

	next unless /^\@\d{14}/;
	my $oldFile = $_;

	# multilog files begin with an @ and are followed by a tai64n
	# number. Processed files have a ".s" suffix and are mode 744.

	my $newFile = $oldFile;
	$newFile =~ s/^\@//;
	$newFile = &time2tai64n($newFile);
	$newFile .= ".s";

	open(NEWFILE, "> $newFile");
	open(OLDFILE, $oldFile);

	while (<OLDFILE>)
	{
	    my ($time, $text) = split(/ /, $_, 2);
	    $time = &time2tai64n($time);

	    print NEWFILE "$time $text";
	}

	close OLDFILE;
	close NEWFILE;

	chmod 0744, $newFile;
	chown $uid, $gid, $newFile;

	unlink $oldFile;
    }
}

closedir DOT;

exit 0;

sub time2tai64n
{
    # Note, this routine is not perfect, but it should survive up to
    # any Y2038 rollover issues :)

    my $time = shift;
    my $tai = "\@40000000";

    my ($integer, $fraction) = split(/\./, $time, 2);
    $fraction = 0 unless defined $fraction;
    $integer += 10;	# Leap second offset?

    return sprintf("%s%08lx%08lx", $tai, $integer, $fraction);
}
