#!/usr/bin/perl
# $Id: rig_main.cgi,v 1.95 2025/08/21 11:11:58 sqko Exp $
############################################################
############################################################
###                                                      ###
###   Originally designed by Soeren Koch                 ###
###                                                      ###
###   Impelemented by Soeren Koch                        ###
###                                                      ###
###   Copyright by Soeren Koch January 20011             ###
###                                                      ###
############################################################
############################################################

use strict;
use warnings;
use CGI qw(:standard :netscape);
use RFC::Main;
use RFC::Rig;
use RFC::RFCCGI qw(:cgi :html);
use RFC::Header;
use Fcntl qw(:DEFAULT :flock);

my $ref = &RFC::RFCCGI::get_user_data_ref();
my $uid = $$ref{'uid'};
my $r = param('rig');
unless ($r)
{
    print header();
    print "No rig specified!\n";
    exit;
}
my $rig = RFC::Rig->new($r);

if (!defined(param))
{
    print process('to_login.tt');
}
else
{
    if ($uid)
    {
        print process('main_nav.tt');
        $_ = param('action');
	$_ = '' unless (defined($_));
      CASE:
        {
	    ### Insert case statements ###
	    /save_comment/i and do {&save(); &main_page; last CASE;}; 
	    &main_page_template;
        }
        print process('end_html.tt');
    }
    else 
    {
        print process('not_auth.tt');
    }
}
exit;



sub main_page_template()
{
    my %data = ();
    $data{'tempcontrol'} = [$rig->list_devices_control('tempcontrol')];
    $data{'relay'} = [$rig->list_devices_control('relay')];
    $data{'water'} = [$rig->list_devices_control('water')];
    $data{'gas'} = [$rig->list_devices_control('gas')];
    my @gasses = $rig->list_devices_control('gas');
    my @list = ();
    foreach my $d ($rig->list_devices_control('multiplex'))
    {
	my $dev = $rig->get_device('multiplex',$d);
	my %h = (
	    'name' => $dev->name(),
	    'label' => $dev->label(),
	    );
	push @list,\%h;
    }
    $data{'multiplex'} = [@list];
    $data{'reload_interval'} = get_cv('global','GUI_reload_time');
    $data{'reload_interval'} = 30 unless ($data{'reload_interval'});
    $data{'reload_interval'} = 5 if ($data{'reload_interval'} < 5);
    my %mgasses = ();
    my %glist = ();
    foreach (@gasses)
    {
	$glist{$_} = 1;
    }
    foreach my $n (@{$data{'multiplex'}})
    {
	my $d = $rig->get_device('multiplex',$$n{'name'});
	next unless ($d);
	my @g = $d->gasses();
	foreach my $gas (@g)
	{
	    $glist{$gas} = 0 unless ($gas eq $d->gas_name());
	}
	$mgasses{$n} = [@g];
    }
    @gasses = ();
    foreach my $gas (sort keys %glist)
    {
	push @gasses,$gas if ($glist{$gas});
    }
    $data{'multiplex_gasses'} = \%mgasses;
    $data{'gas'} = [@gasses];
    $data{'analog'} = [$rig->list_devices_control('analog')];
    my %amodes = ();
    foreach my $n (@{$data{'analog'}})
    {
	my $d = $rig->get_device('analog',$n);
	next unless ($d);
	$amodes{$n} = $d->mode();
    }
    $data{'analog_modes'} = \%amodes;
    $data{'PSU'} = [$rig->list_devices_control('PSU')];
    $data{'PID'} = [$rig->list_devices_control('PID')];     
    $data{'is_iv'} = $rig->is_iv();
    my $dir = $rig->webdir();
    my $start_by = undef;
    my $start = undef;
    my $f = $dir.'proglog';
    my $i = $dir.'info.txt';
    if ($i && -e $i)
    {
	open MYIN,'<',$i or die "Cant open file $i for reading $!";
	while (my $str = <MYIN>)
	{
	    if ($str && $str =~ /test started at \s+(.+)$/i)
	    {
		$start = $1;
	    }
	    if ($str && $str =~ /test started by:\s+(.+)$/i)
	    {
		$start_by = $1;
	    }
	    if ($str && $str !~ /test started by/i && $str =~ /test started\s+(.+)$/i)
	    {
		$start = $1;
	    }
	    last if ($start && $start_by);
	}
	close MYIN;
    }
    if ($f && -e $f && !($start && $start_by))
    {
	open MYIN,'<',$f or die "Cant open file $f for reading $!";
	my $str = <MYIN>;
	close MYIN;
	if (!$start && $str && $str =~ /^([\w\s]+)\s\d+\:\d+\:\d+\s(\d+)/)
	{
	    $start = $1.' '.$2 unless ($start);
	}
	if (!$start_by && $str && $str =~ /user\s\'(\w+)\'/)
	{
	    $start_by = $1;
	}
    }
    my $cmd = "tail -1 $dir/jdata";
    my $res = `$cmd`;
    if ($res && $res =~ /^\s*([\d\.]+)/)
    {
	$data{'runtime'} = $1;
    }
    unless ($start)
    {
	$cmd = "head -1 $dir/jdata";
	$res = `$cmd`;
	if ($res && $res =~ /utime\s*(\d+)/)
	{
	    $start = localtime($1);
	}
    }
    $data{'start'} = $start;
    $data{'start_by'} = $start_by;
    
    ## Legacy mode ##
    $data{'legacy'}{'tnames'} = [$rig->get_cv('userinterface','temp')];
    $data{'legacy'}{'gnames'} = [$rig->get_cv('userinterface','gas')];
    $data{'legacy'}{'vnames'} = [$rig->get_cv('userinterface','voltage')];
    $data{'legacy'}{'cnames'} = [$rig->get_cv('userinterface','current')];
    $data{'legacy'}{'anames'} = [$rig->get_cv('userinterface','alert')];
    $data{'warning_message'} = $rig->get_cv('main','warning_message');
    print process('rig_main.tt',&get_template_data_ref(\%data));
}


sub save
{
    return unless ($$ref{'allow_log'} || ($$ref{'auth'}));
    my $string = get_CGI_value('comments');
    my $time = localtime();
    my $user = $$ref{'name'};
    my $str = $time.', User '.$user.' added: '.$string."\n";
    if (param('filename'))
    {
	my $prefix = '';
	my $id = 'filename';
	eval {
	    my $dir = $rig->webdir().'/uploads/';
	    unless (-d $dir)
	    {
		mkdir $dir;
	    }
	    use constant BUFF => 16_384;
	    use constant MAX_F_SIZE => 16 * 1_048_576; ### 16 MB ###
	    use constant MAX_DIR_SIZE => 800 * 1_048_576; ### 800 MB ###
	    use constant MAX_OPEN_TRIES => 100;
	    $CGI::DISABLE_UPLOADS = 0;
	    $CGI::POST_MAX = MAX_F_SIZE;
	    opendir DIR, $dir or do {
		die "Unable to open $dir: $!";
	    };
	    my $dir_size = 0;
	    foreach ( readdir DIR )
	    {
		$dir_size += -s "$dir/$_";
	    }
	    close DIR;
	    if ( $dir_size + $ENV{CONTENT_LENGTH} > MAX_DIR_SIZE)
	    {
		die "Error: Upload dir '$dir' is full, please increase the file space!";
	    }
	    my $filen = param($id);
	    $filen =~ s/\s+/_/g;
	    chomp $filen;
	    if ($filen =~ /(\w[\w\.\-\s]*)$/)
	    {
		my $filen = $prefix.$1;
		my $fh = upload($id);
		if (!$fh)
		{
		    die "Error: Undefined filehandle: \'$fh\' associated with file upload field \'$id\' with value \'$filen\'. No file uploaded!";
		}
		if ($filen !~ /\_\.?\w*$/)
		{
		    $filen =~ s/(\.?\w*)$/\_0$1/;
		}
		until (sysopen OUTPUT, $dir. $filen, O_CREAT | O_RDWR | O_EXCL )
		{
		    $filen =~ s/(\d*)(\.?\w*)$/($1||0)+1 . $2/e;
		    $1 >= MAX_OPEN_TRIES and do
		    {
			die "Error: Unable to get unique name $filen for file upload in ABFdb::file_upload().";
		    };
		}
		my $buff = undef;
		while (read($fh,$buff, BUFF))
		{
		    print OUTPUT $buff;
		}
		close OUTPUT;
		$str .= "File uploaded: /uploads/$filen";
	    }
	};
	if ($@)
	{
	    $rig->errorlog($@);
	}
    }
    my $content = $rig->info($str);
}


