#!/usr/bin/perl -wT
# $Id: logfile.pl,v 1.20 2023/12/18 06:13:47 sqko Exp $
use strict;
use warnings;
use RFC::Rig;
use RFC::Visitor;
use RFC::Main;
use RFC::Header;
use SemaforeFile;
use Fcntl qw/:DEFAULT :flock/;
use sigtrap qw(die INT QUIT);
use sigtrap qw(die untrapped normal-signals stack-trace any error-signals);

my $rig = RFC::Rig->new(shift);
$rig->check_run;
my $localecho = 0;
my $ignore = 0;
my $debug = 0;
my $conf = 0;
my $caching = 0;
my $print_kanal = 1;
my $cnf = RFC::Main::get_cv('admin','save_raw_kanaldata');
$print_kanal = 0 if ($cnf && $cnf =~ /no/i);
while (@ARGV)
{
    $localecho = 1;
    my $item = shift;
    $rig->set_debug(4) if ($item =~ /debug/i);
    $conf = 1 if ($item =~ /conf/i);
    $ignore = 1 if ($item =~ /ignore/i);
    $caching = 1 if ($item =~ /cach/i);
    if ($item =~ /debug/i)
    {
	$debug = 1;
	if ($item =~ /\=(\d)/)
	{
	    $debug = $1;
	}
    }
}
$rig->set_debug($debug) if ($debug);
if ($conf)
{
    warn '######################################################',"\n";
    warn '###                                                ###',"\n";
    warn '###     Checking configuration only!               ###',"\n";
    warn '###                                                ###',"\n";
    warn '######################################################',"\n";
    my $v = RFC::ConfigVisitor->new();
    $rig->Accept($v);
    warn join("\n",$v->result()),"\n";
    $rig = undef;
    exit;
}

my $test = $rig->session;
if (!$ignore && $rig->is_iv)
{
    $rig = undef;
    sleep(1);
    exit; 
}
my $dat = `date +"%Y:%m:%d"`;
$dat =~ /([\d\:]*)/;
$dat = $1;



my $homedir = $RFC::Header::publicdir . 'rig' . $rig->name . "/" . $rig->name . 'test' . $test;
my $localdatadir = $RFC::Header::userdir.'rig' . $rig->name . "/" . $rig->name . 'test' . $test;
if ( !( -d $localdatadir ) ) { system("mkdir $localdatadir") }

$| = 1;
my $lockfile = '/home/celltest/rig_'.$rig->name.'_logfile.lock';
unless (-e $lockfile)
{
    sysopen(MFH, $lockfile, O_WRONLY | O_CREAT) or CORE::die "Error: Could not open $lockfile $!";
    chmod 0666, $lockfile;
    close MFH;
}
my $raadata = $homedir.'/raadata.'.$dat;
my $kanaldata = $localdatadir.'/kanaldata.'.$dat;
my $f = SemaforeFile->new($raadata,$lockfile);
my $k = SemaforeFile->new($kanaldata,$lockfile);
$f->debug($rig->debug);
$k->debug($rig->debug);

###########################################################
#### Aquire lock to ensure only one instance pr rig #######
#### at any given time                              #######
###########################################################
my $is_locked = $f->lock_ex_nb;
if ( $is_locked == 0 ) {
    unless ($ignore)
    {
	$rig = undef;
	sleep(1);
	exit; 
    }
    ## Upgrade to blocking lock and wait if nescesarry to awoid race condition ###
    ## Nescesarry for iV-curve logging ###
    $f->lock_ex(); 
}
if ($caching)
{
    $rig->allow_cache(1) 
}
my $outstring = $rig->readstring;
my $kanalstring = $rig->kanaldata;
if ($rig->get_cv('datalog','additional_log_program'))
{
    my $file = $RFC::Header::libdir.'logprograms/'.$rig->get_cv('datalog','additional_log_program');
    if (-e $file && -x $file)
    {
	my $args = $rig->get_cv('datalog','log_program_arguments');
	$args = '' unless ($args);
	my $cmd = $file.' '.$args;
	my $res = `$cmd`;
	if ($res)
	{
	    chomp $res;
	    $outstring .= ' '.$res; 
	}
    }
}
###################################################################
##### Print result to file and standard output if local echo ######
###################################################################
print $outstring,"\n" if ($localecho);
$f->append($outstring);
if ($print_kanal)
{
    $k->open_append_unsafe;
    my $fh = $k->fh;
    print $fh $kanalstring,"\n";
    $k->close;
}
$f->lock_un;
$rig = undef;
sleep(1);
exit;

