#!/usr/bin/perl
#
# Copyright (C) 2004 Daniele Giacomini daniele@swlibero.org
#
# 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., 675 Mass Ave, Cambridge, MA 02139, USA.
#
#
#
#
#
# cat FILE | mathopd_to_clf
#
# Will create a CLF (Common Log Format) file for each virtual domain
# inside FILE. The FILE is an access log generated by Mathopd HTTP
# server.
#
#
my ($line) = "";
my ($output) = "";
my ($previousServerName) = "";
#
while($line = <STDIN>)
  {
    my (@mathopd_log)   = split(/\t/, $line);
    my ($Ctime)         = $mathopd_log[0];
    my ($RemoteUser)    = $mathopd_log[1];
    my ($RemoteAddress) = $mathopd_log[2];
    my ($RemotePort)    = $mathopd_log[3];
    my ($ServerName)    = $mathopd_log[4];
    my ($Method)        = $mathopd_log[5];
    my ($Uri)           = $mathopd_log[6];
    my ($Stats)         = $mathopd_log[7];
    my ($ContentLength) = $mathopd_log[8];
    my ($Referer)       = $mathopd_log[9];
    my ($UserAgent)     = $mathopd_log[10];
    my ($BytesRead)     = $mathopd_log[11];
    my ($BytesWritten)  = $mathopd_log[12];
    #
    if ($ServerName eq "-")
      {
        #
	# Just ignore it.
	#
        next;
      }
    #
    my (@date)          = split(/\s+/, $Ctime);
    #
    if ($Referer eq '-')
      {
        $Referer = '';
      }
    #
    $output = sprintf ("%s - - [%02d/%s/%s:%s +0000] \"%s %s HTTP/1.0\" %d %d \"%s\" \"%s\"",
                       $RemoteAddress,
		       $date[2], $date[1], $date[4], $date[3],
		       $Method,
		       $Uri,
		       $Stats,
		       $ContentLength,
		       $Referer,
		       $UserAgent);

    if    ($previousServerName eq "")
      {
        open (OUTPUT, ">>:utf8", $ServerName);
      }
    elsif ($previousServerName eq $ServerName)
      {
        #
	# The output stream is already opened.
	#
        ;
      }
    else
      {
        close (OUTPUT);
        open (OUTPUT, ">>:utf8", $ServerName);
      }
    #
    print OUTPUT ("$output\n");
  }
close (OUTPUT);
