#! /usr/bin/perl
# script to backup solenoid settings using "burtrb"
# author Yi Qiang, yqiang@jlab.org

use strict;
use warnings;
use Tk;

if(@ARGV < 1){
    print "Error: no input specified, exiting!\n";
    exit(1);
}
elsif(@ARGV > 1){
    print "Error: too many input parameters, exiting!\n";
    exit(2);
}

# change input name to lowercase
my $input_name = $ARGV[0];
$input_name =~ tr/A-Z/a-z/;
my $snap_dir = "/gluex/data/burt/solenoid/";

my $found = 0;
my @names = ("alarm","valve");
foreach my $name(@names){
    if($name eq $input_name){
        $found += 1;
    }
}

if($found<1){
    print "Error: wrong input name specified, exiting!\n";
    exit(3);
}
else{
    $snap_dir = $snap_dir.$input_name;
    &SelectBackupFile($input_name, $snap_dir);
}

exit(0);

# subroutine to select a file
sub SelectBackupFile{
    our $list_name = $_[0];
    my $snap_dir = $_[1];

    # create the text entry widget
    our $tk_main = MainWindow->new;
    $tk_main->title("Select File Name" );
 
    my $win_label = sprintf( "\t\tSelect Backup File Name for $list_name\t\t\t\t");
    my $tk_label = $tk_main->Label(-text=>$win_label);
    $tk_label -> pack;
    
    my $date_var = `date`;
    chop($date_var);
    my @date_list = split(/\s+/, $date_var) ;
    my $month = $date_list[1];
    my $day   = $date_list[2];
    my $year  = $date_list[5];
    my $hour  = $date_list[3];
    $hour =~ s/\:/\_/g ;

    print "M: $month D: $day Y: $year H: $hour \n";

    our $file_name = sprintf("%s/%s_%s_%s_%s_%s.snap", $snap_dir,
                         $list_name, $day, $month, $year, $hour);

    my $tk_entry = $tk_main->Entry(-textvariable=>\$file_name);
    $tk_entry->pack(-expand=>1, -fill=>'x');

    my $tk_ok_button = $tk_main->Button(-text=>'SAVE',
                                        -command=>[\&Save_File]);
    $tk_ok_button -> pack(-side=>'left', -padx=>2);

    my $tk_dismiss = $tk_main->Button(-text=>'CANCEL',
                                      -command=>[$tk_main=>'destroy']);
    $tk_dismiss -> pack(-side=>'right', -padx=>2);

    $tk_entry->focus();
    
    MainLoop;
}

sub Save_File{
    our $list_name;
    our $file_name;
    our $tk_main;

    $list_name =~ tr/A-Z/a-z/;
    my $req_dir = "REQS";
    my $command = "burtrb -f $req_dir/solenoid_".$list_name.".req > $file_name";

    print "Command is : $command \n";
    system "$command" || die "Could not execute $command \n";

    $tk_main->destroy;
}

