#!/usr/bin/perl
#$Id: new_device.cgi,v 1.11 2015/04/26 12:20:44 sqko Exp $
use strict;
use warnings;
use RFC::Rig;
use RFC::Main;
use RFC::RFCCGI qw(:cgi :html);
use CGI qw(:standard :netscape);

my $r = param('rig');
unless ($r)
{
    print header();
    print "No rig specified!\n";
    exit;
}

my $rig = RFC::Rig->new($r);

my $acmode = get_cv('global','access_mode');
$acmode = 'celltest' unless ($acmode);
print header();
my $usermode = user_auth($acmode,'m');
if (RFC::RFCCGI::rig_mode())
{
    ####  Read and use mode deprecated after initialisation of rig authentification ####
    $usermode = 1;
}
unless (RFC::RFCCGI::rig_auth())
{
    $usermode = 0;
}

unless (login_ok() && $usermode)
{
    print "Warning: You asre not authorised to change parameters on rig ".$rig.", changes aborted!";
    exit;
}

my $ac = param('action');
unless ($ac)
{
    print "";
    exit;
}

### Ok, if we got here, the user is authenticated and a action parameter is specified

if ($ac eq 'new_device')
{
    my $type = param('type');
    my $value = param('value');
    if ($type =~ /group/)
    {
	$value = uc($value);
    }
    unless ($type && $value)
    {
	print "Warning: Type or name (value) not specified for creating new device for rig ".$rig->name;
	exit;
    }
    my $i = 0;
    if ($type eq 'multiplex' && $value !~ /^\d+$/)
    {
	print "Warning: Multiplexer devices may only have integers as names!";
	exit;	
    }
    my @devicelist = $rig->list_types();
    my @list = $rig->avaliable_devices($type);
    my $found = 0;
    foreach (@list)
    {
	$found = 1 if ($_ eq $value);
    }
    if ($found)
    {
	print "Error: device $value of tyle $type does already exist, aborting!\n";
	exit;	
    }
    my $section = $rig->device_sectionname($type).$value;
    $rig->begin;
    $rig->change_config_value($section,'title','');
    if ($type eq 'MFC')
    {
	CGI_client($rig->name,'touch_file','MFC_'.$value);
    }
    if ($type eq 'gas')
    {
	CGI_client($rig->name,'touch_file','gas_'.$value);
	$rig->change_config_value($section,'mode','Manual');
	$rig->change_config_value($section,'controler',0);
    }
    if ($type eq 'water')
    {
	CGI_client($rig->name,'touch_file','water_'.$value);
    }
    eval {
	### Check for valid data ###
	$rig->init();
	$rig->commit;
    };
    if ($@)
    {
	$rig->rollback;
	print "Error: change resulted in an invalid configuration, issuing rollback; error: $@";
	print "$type\n";
	print "$value\n";
	exit;
    }
    print "OK\n";
    print "$type\n";
    print "$value\n";
    print "\n";
    exit;    
}
