#!/usr/bin/perl -wT
#
# TWiki Collaboration Platform, http://TWiki.org/
#
# Copyright (C) 2000-2004 Peter Thoeny, peter@thoeny.com
# Copyright (C) 2002 Richard Donkin, rdonkin@bigfoot.com
#
# For licensing info read license.txt file in the TWiki root.
# 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, published at 
# http://www.gnu.org/copyleft/gpl.html
#
# DESCRIPTION
# This script updates the usage statistics of each TWiki web.
# It reads the current month's log file and updates the table
# in the WebStatistics topic of each web.
# The script should be called by a cron job, it is recommended to
# call it once a day.
BEGIN {
    # Set default current working directory
    if( $ENV{"SCRIPT_FILENAME"} && $ENV{"SCRIPT_FILENAME"} =~ /^(.+)\/[^\/]+$/ ) {
        chdir $1;
    }
    # Set library paths in @INC at compile time
    unshift @INC, '.';
    require 'setlib.cfg';

    # 'Use locale' for internationalisation of Perl regexes -
    # main locale settings are done in TWiki::setupLocale
    # Do a dynamic 'use locale' for this module
    require TWiki;
    if( $TWiki::useLocale ) {
        require locale;
	import locale ();
    }
}

use CGI::Carp qw(fatalsToBrowser);
use CGI;
use TWiki;
use TWiki::UI::Statistics;

#open(STDERR,'>&STDOUT');   # redirect error to browser
# FIXME: Beware global $| in mod_perl!  Should use 'local'
$| = 1;                    # no buffering

my $query = undef;
my $pathInfo = "";
my $remoteUser = "";
my $topic = "";
my $logDate = "";

# determine at runtime if script is called by browser or cron job
if( $ENV{'DOCUMENT_ROOT'} ) {
  # script is called by browser
  $query = new CGI;
  $pathInfo = $query->path_info() || ""; 
  $remoteUser = $query->remote_user() || "";
  $topic = $query->param( 'topic' ) || "";
  $logDate = $query->param( 'logdate' ) || "";

} else {
  # script is called by cron job or user
  foreach my $arg ( @ARGV ) {
    if ( $arg =~ /^-web=(.*)$/o ) {
      $pathInfo = "/$1";
    } elsif ( $arg =~ /^-logdate=(.*)$/o ) {
      $logDate = $1;
    }
  }
}

TWiki::UI::Statistics::statistics( $query, $pathInfo, $remoteUser, $topic, $logDate );

# =========================
# EOF
