#!/usr/bin/perl -w
#
# $Revision: #1 $
#
# upgrade_swfw - perform upgrade of switch firmware
#

use	Carp;
use	IO::Handle;
use	File::Basename;

require "stat.pl";
require "getopts.pl";

$opt_G          = 0;            # GUI mode
$outputfile     = "/var/log/eq_upgrade.log";


sub get_answer {
    my $ans = "x";
    chop($ans = <STDIN>);
    return($ans);
}

#
# cark - cark it
#

sub cark {
    my $arg = shift;
    print "**** Fatal error.\n";
    print "**** Please contact CoyotePoint customer support.\n";
    die "$arg";
}

#
# sis - perform `system' function and croak if non-zero result.
#

sub sis {
    my $arg = shift or &cark("");

    #
    # This is perl-ass-backwards, if you can imagine what that is.
    #
    system $arg and sleep 1 and &cark("\n");
}

#
# switch_firmware
#    
    sub switch_firmware {
	my $lfirm = "";
        my $cfirm = "";
	my $fw_ok = 0;
	my @latest = (0, 0);
        my @current = (0, 0);

        open SW, "/usr/l7up/swconfig -d 2>&1 |" or &cark("$!\n");

        while (<SW>) {
            if (/(Latest)/) {
               $lfirm = $_;
	       @latest = split(/\t/, $lfirm);
            }
            if (/(Current)/) {
               $cfirm = $_;
               @current = split(/\t/, $cfirm);
            }
        }
        close SW;
	
        if ($current[1] < $latest[1]) {
            print "\nWARNING: This upgrade contains firmware which\n";
	    print "requires an immediate reboot after installation.\n";
            print "If you proceed, a system reboot will be automatically\n";
	    print "performed when the upgrade is complete.\n"; 
	    $fw_ok = 1;
        }   
	else {
	    $fw_ok = 0;
	}    
	flush STDOUT;
	flush STDERR;
	sleep 1;
	return $fw_ok;
    }	
    
  
#    
# main
#    
    sub main {
        my $gx = 0;    # Indicates GX platform
	my $fw_ok = 0;    
        &Getopts('G');
	        
	if ($opt_G) {
	    open(STDOUT, '>>'.$outputfile ) or die $!;
	    open(STDERR, '>>'.$outputfile ) or die $!;
	}			            
        select(STDOUT); $| = 1; 
        select(STDERR); $| = 1;
		
	#
	# See if this is a gx platform
	#
	open IN, "/usr/local/sbin/lm -h -U 2>&1 |" or &cark("$!\n");

        while (<IN>) {
            if (/^(e[2346]50)gx-?/) {
                $gx = 1;
            }
        }
	
	#
	# Check switch firmware level 
	#
	if ($gx) {
	    $fw_ok = &switch_firmware;
	}    
	
	exit $fw_ok;
    }

    &main;
