#!/usr/bin/perl -w

## Author: Alois Mahdal at zxcvb cz
# Back-end for very primitive remote logging. Front-end is htlogr.pm

# 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 3 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, see <http://www.gnu.org/licenses/>.

use CGI;

my $LOG_FILE = '/var/log/htlogr.log';
open my $fh, ">>", $LOG_FILE or die "cannot open log file for appending: $!";

sub stamp {
    my $unixtime = ($_[0] ? $_[0] : time );
    my ($sec, $min, $hour, $mday, $mon, $year) = localtime $unixtime;
    return sprintf (
        "%04i-%02i-%02i %02i:%02i:%02i",
        $year + 1900,   $mon + 1,   $mday,
        $hour,          $min,       $sec
    );
}

my $q = CGI->new;
my $msg = ( defined $q->param('msg')    ? $q->param('msg')  : '-' );
my $tag = ( defined $q->param('tag')    ? $q->param('tag')  : '-' );
my $i   = ( defined $q->param('i')      ? $q->param('i')    : '-' );

my $message = sprintf("Time: %s; Origin: %s; Tag: %s; I: %s; Message: %s\n",
    &stamp(time),
    $ENV{'REMOTE_ADDR'},
    $tag,
    $i,
    $msg
);


print $fh $message;

my $out = "Message logged: $msg\n";

print $q->header(
    -type               => 'text/plain',
    -expires            => 'now',
    -content_lentgth    => length $out,
    -connection         => 'close'
);

print $out;

close $fh or die "cannot close log file: $!";