#! /usr/bin/perl -w
#
#  AlarmCtrl controls the alarm manager (AlarmMgr) process via the Alarm
#  command l ine client.
#
#  Commands currently available are:
#
#  help
#  restart
#  snapshot <file>
#  setup <file>
#
sub snapshot; sub setup;
#
# ---> Check command syntax
$syntax = 0;
if (@ARGV < 1) {
   print ("Error in command");
   $syntax = 1;
}

# ---> Get the command and file name
$Cmd = $ARGV[0];
if (@ARGV < 2) {
   $File = "/tmp/alarm_ctrl_snapshot.txt";
} else {
   $File = $ARGV[1];
}

#
# ---> Get the command and file name
$Cmd = $ARGV[0];
if (@ARGV < 2) {
   $File = "/tmp/alarm_ctrl_snapshot.txt";
} else {
   $File = $ARGV[1];
}

#
# ---> Execute the appropriate command
if ($Cmd eq "snapshot") {
    snapshot();
} elsif ($Cmd eq "restart") {
    $syntax = snapshot();
    if (! $syntax && -f $File) {
        system("pkill AlarmMgr");
	sleep(5);
        setup();
    }
} elsif ($Cmd eq "setup") {
    setup();
} elsif ($Cmd eq "help") {
    $syntax = 1;
} else {
    print("Undefined command: $Cmd\n");
    $syntax = 1;
}

#
# ---> Error?
if ($syntax) {
   print("AlarmCtrl make a snapshot of the Alarm Manager tables\n");
   print("The AlarmCtrl command line syntax is:\n");
   print("AlarmCtrl {help | restart | snapshot | start} [<file>]\n");
}

#
# --> Take a snapshot of the Alarm database.
sub snapshot {
    open (SNAPFILE, ">$File");
    $AlarmDef = `Alarm getdefined`;
    chomp $AlarmDef;
    $AlarmDef  =~ s/^Defined alarms: //;
    @AlarmList = split(/ /, $AlarmDef);
    for my $alarmID (@AlarmList) {
    	if ( $alarmID =~ '(.*):(.*)' ) {
           my $defCmd = `Alarm dumptemplate $1 $2`;
	   chomp $defCmd;
	   print (SNAPFILE "$defCmd\n");
    	} else {
	   print("Error in alarm list element: $alarmID\n");
	   return 1;
        }
    }
    close(SNAPFILE);
    return 0;
}

#
# --> Take a snapshot of the Alarm database.
sub setup {
    system("bash -c 'source $File'");
}