package Common::Log;

use strict;
use warnings;
use lib $ENV{'CF_SYSTEM_ROOT'}.'/lib/common/perl';

use Fcntl ':flock';
use Exporter;
use Common::Time;

our @ISA = qw(Exporter);
our @EXPORT = qw(write_log);


## Parameters:
##    log file name
##    log message || 'check'
##    options: {'script_name'=>0}
sub write_log {
	my $log_fname = shift || die "Log filename should be defined!";
	my $msg = shift;
	my $opt = shift || {};

	$msg = 'check'
		unless $msg;

	my ($hr,$mn,$sc) = whattime();
	my ($d,$m,$y) = whatday();

	my $datetime_stamp = "$d.$m.$y $hr:$mn:$sc";

	my $ip = '';
	$ip = "\t$ENV{'REMOTE_ADDR'}"
		if (exists($ENV{'REMOTE_ADDR'}));
	$ip .= " $ENV{'HTTP_X_FORWARDED_FOR'}"
		if (exists($ENV{'HTTP_X_FORWARDED_FOR'}));

	my $who = $0;

	$who = ''
		if( defined $opt->{'script_name'} && $opt->{'script_name'}==0 );

	my $old_umask = umask(0);

	return "Can't open logfile '$log_fname': $!!"
		unless( open(LOG, ">>$log_fname") );

	flock(LOG, LOCK_EX);
	print LOG $datetime_stamp.' '.($ip ? $ip.' ' : '').($who ? $who.' ' : '').$msg."\n";
	flock(LOG, LOCK_UN);
	close(LOG);

	umask($old_umask);

	return undef;
}


1;
