eval '(exit $?0)' && eval 'exec perl -S $0 ${1+"$@"}'
    & eval 'exec perl -w -S $0 $argv:q'
    if 0;

BEGIN { unshift @INC, "/usr/mellanox/miniperl" }

use strict;

my $my_version = "gz_burn (Mellanox Gazelle Burn Tool) V1.9 0002";

#------------------------------------------------------------------
#                            includes
#------------------------------------------------------------------
unshift @INC, "/usr/mst/etc";

require "hw_def.ptxt";
require "gz_trace.ptxt";

use Getopt::Long;

our ($gazelle_i2c, $gnu_i2c);
###our ($cr_def, $binfo, $binfo_st, $einfo, $einfo_st);
our ($cr_def, $binfo, $binfo_st, $einfo);

#------------------------------------------------------------------
#                            variables
#------------------------------------------------------------------
my      $device;        # Current device
my      $con_bus=0;     # Connected bus
my      $op_pat;

my      $present_leaf=-1;
my      $present_spine=-1;
my      %present=();
my      %rev_info=();

# Configuration
my      %config=
        (
                hw      => { val=>"gazelle_i2c", descr=>"HW Device Type" },
                mst_dev => { val=>"/dev/mst/mtusb", descr=>"MST device name" },
                image   => { val=>"", descr=>"Image" },
                bsn     => { val=>"", descr=>"BSN" },
                guid    => { val=>"", descr=>"GUID" },
                emt     => { val=>"eburn", descr=>"How to run burn tool" },

                status          => { val=>0 },

                pat     => { val=>"*", descr=>"Bus Pattern" },
                burn            => { val=>0 },
                bi              => { val=>0 },          # burn blade info eeprom
                bv      => { val=>($binfo->[$binfo_st->{ver}]->{val}), descr=>"BladeInfoVersion"},
                retry   => { val=>"3", descr=>"Number of retryes" },

                c               => { val=>0 },
                T               => { val=>0 },

                help            => { val=>0 },
                man             => { val=>0 },
                ver             => { val=>0 },

                help_trace      => { val=>0 },
                trace           => { val=>0 },
                no_color        => { val=>0 },

                leaf_con        => { val=>0 },
                spine_con       => { val=>0 },
        );

#------------------------------------------------------------------
#                            get_connect_point
#------------------------------------------------------------------
# Descr: Determine connection point
# Input: $con - desired con point, 0-autodetect
# Retrn: pointer to hash of bus to which we are connected
#------------------------------------------------------------------
sub get_connect_point {

        my $con = shift @_;     # Desired point


        # Check connection from desired point
        if( $con ){
                if( $con->{is_con}->( $con ) ){
                        return $con;
                }
                else {
                        xerror( 1, "No connection to $device->{hw_name} $con->{bus_name}\n" );
                        return 0;
                }
        }

        #
        # Autodetect
        #
        
        # check primary bus
        if( $device->{pri_bus}->{is_con}->( $device->{pri_bus} ) ) {
           return $device->{pri_bus};
        }
        
        # check secondary buses
        foreach my $bus_dev_key ( sort keys( %{$device->{pri_bus}} ) ){
        
           # take only bus capable devices ( switch )
           next unless $bus_dev_key =~ /sw/i;
        
           # check if we are connected to one of secondary bus under device
           my $bus_dev = $device->{pri_bus}->{$bus_dev_key};         # Take sw device
           foreach my $sec_bus_key ( sort keys( %{$bus_dev} ) ){
              if( $sec_bus_key =~ /bus/ and exists $bus_dev->{$sec_bus_key}->{is_con} ){
                 if( $bus_dev->{$sec_bus_key}->{is_con}->( $bus_dev->{$sec_bus_key} ) ){
                    return $bus_dev->{$sec_bus_key};
                 }
              }
           }
        }
        
        # if we get here no connection was found
        xerror( 1, "No connection to $device->{hw_name}\n" );
        return 0;
}



#------------------------------------------------------------------
#                            follow_bus
#------------------------------------------------------------------
# Descr: Touch devices on bus and subbuses
# Input: top_bus-starting point
#        sw_dev - switch device for top_bus
#        operation to do on entering bus
#           SWITCH   - try to switch on bus
#           CONNECT  - check if bus connected
#           PAT_HOOK - do not call hook if patternnot matching
#        level-current recurcion level
#        [hook] - optional function to be called as $hook->(bus,level,dev_name)
#                 hook return code is used by follow_bus
#                   (-2) - leave bus
# Retrn:
#------------------------------------------------------------------
sub follow_bus {

    my $top_bus = shift @_;
    my $sw_dev  = shift @_;
    my $opcode  = shift @_;
    my $level   = shift @_;
    my $hook    = shift @_;

    my $rc;

    # Operations on new bus
    if( $opcode =~ /CONNECT/ ){
            # check connect
            if( $top_bus->{is_con} ){
                    if( ! $top_bus->{is_con}->($top_bus) ){
                            return 0;
                    }
            }
    }
    if( $opcode =~/SWITCH/ ){
            # Switch to top_bus
            if( $sw_dev ){
                    $sw_dev->{sw_func}->( $sw_dev, $top_bus ) if exists $sw_dev->{sw_func};
            }
    }

    # Follow all keys starting from dev
    foreach my $dev_name ( sort grep {/^dev*/} keys %{$top_bus} ){

        # call hook
        if( !($opcode =~/PAT_HOOK/) or $top_bus->{bus_addr} =~ /$op_pat/ ){
                $rc = $hook->( $top_bus, $level, $dev_name ) if( $hook );
                return if $rc==-2;
        }

        if( $dev_name=~/sw/ ){
            map follow_bus($top_bus->{$dev_name}->{$_}, $top_bus->{$dev_name}, $opcode, $level+1, $hook ),
                                        sort grep {/bus/} keys %{$top_bus->{$dev_name}};
        }
    }
}


#------------------------------------------------------------------
#                            print_topology
#------------------------------------------------------------------
# Descr: Print hw device topology
# Input:
# Retrn:
#------------------------------------------------------------------
sub print_topology {
        print "Topology for hw device \"$device->{hw_name}\"\n";
        print "===========================================\n";

        follow_bus( $device->{pri_bus}, 0, 0, 0,
                sub{ print " " x ($_[1]*3);
                     printf("%10s bus:%s addr:%s\n",
                        $_[2],                          # Dev name
                        $_[0]->{bus_addr},              # Bus addr
                        $_[0]->{bus_name},              # Bus name
                        $_[0]->{$_[2]}->{dev_addr}      # Dev addr
                     );
                });

        print "===========================================\n\n";
}

my $STAT = {};
my %GUID = ();

sub check_guid {
    my $devname = shift;
    my $info = shift;

    if ($info->{GUID} =~ /ffffffffffffffff/i
        || $info->{GUID} =~ /0000000000000000/) {
        print "ERROR: $devname: bad GUID\n";
        return;
    }
    if (defined $GUID{$info->{GUID}}) {
        print "ERROR: $devname: duplicate GUID, same as $GUID{$info->{GUID}}\n";
    } else {
        $GUID{$info->{GUID}} = $devname;
    }
}

sub check_bsn {
    my $devname = shift;
    my $info = shift;

    if ($info->{BSN} !~ /^MT/) {
        print "ERROR: $devname: bad BSN\n";
        
    }
}

sub check_fw {
    my $devname = shift;
    my $info = shift;

    if ($info->{FW} !~ /^04\.02\.0005/
        && $info->{FW} !~ /^05\.\d{2}\.\d{4}/) {
        print "ERROR: $devname: bad FW version\n";
    }
}

# list of sanity checks:
# 
# - GUID is good
#       Check GUID is not 0xFFFFF or other not valid guid.
# - Duplicated guids
#       Check there is no duplicated GUID's in Gazelle
# - BSN is good
#       Check that BSN is valid and compliant to BSN format.
# - BSN is same for all devices on blade
#       On Leaf/Spine BSN is stored in each Anafa and in blade info EEPORM.
#       They have to be same over entire blade
# - FW Version is good
#       Check that FW version is reasonable number. Possible versions are
#       4.2.5
#       5.x.x

sub sanity_checkers {
print "\n\nPROBLEM SUMMARY ======================================================\n";

    %GUID = ();
    foreach my $blade (keys %$STAT) {
        foreach my $dev (keys %{$STAT->{$blade}}) {
            if ($dev ne "CH") {
                check_guid ("${blade}${dev}", $STAT->{$blade}->{$dev});
                check_bsn ("${blade}${dev}", $STAT->{$blade}->{$dev});
                if ($STAT->{$blade}->{$dev}->{BSN} !~
                            m/$STAT->{$blade}->{CH}->{BSN}/) {
                    print "ERROR: ${blade}${dev}: bad BSN, doesn't match ${blade}CH\n";
                }
                check_fw ("${blade}${dev}", $STAT->{$blade}->{$dev});
#                print $blade, $dev,
#                        "FW:$STAT->{$blade}->{$dev}->{FW} ",
#                        "GUID:$STAT->{$blade}->{$dev}->{GUID} ",
#                        "BSN:$STAT->{$blade}->{$dev}->{BSN}\n";
            } else {
                check_bsn ("${blade}${dev}", $STAT->{$blade}->{$dev});
#                print $blade, $dev,
#                        "VER:$STAT->{$blade}->{$dev}->{VER} ",
#                        "BSN:$STAT->{$blade}->{$dev}->{BSN}\n";
            }
        }
    }
}

    
#------------------------------------------------------------------
#                       status_report
#------------------------------------------------------------------
# Descr: Print status of all found anafa devices
# Input:
# Retrn:
#------------------------------------------------------------------

sub status_report {

    print "$con_bus->{bus_name} Status Report\n";
    print "------------------------------------\n";
    follow_bus( $con_bus, 0, "CONNECT,PAT_HOOK", 0, \&do_status_report );

    sanity_checkers ()
        if ($con_bus == $gazelle_i2c->{pri_bus});
}

sub do_status_report {

        my $bus = shift @_;
        my $level = shift @_;
        my $dev = shift @_;
        my %status;
        my %info;
        my $reg;
        my $size;

        if( $dev =~ /anafa/ ){

                # Switch to current bus
                return -1 if i2c_sw( $bus->{bus_addr} );

                # Read Version Info
                i2c_read ( 0x5a, 2, $cr_def->{$dev}->{makesn},\$reg, 0, "x 4" );
		$status{makesn} = hex($reg);
                i2c_read ( 0x5a, 2, $cr_def->{$dev}->{fw_version}, \$reg, 0, "x 4" );
		$reg = hex($reg);
                $status{fw_ver_major} = $reg & 0xFF ;
                $status{fw_ver_minor} = ($reg >> 8) & 0xFF;
                $status{fw_ver_subminor} = ($reg >> 16) & 0xFFFF;

                # Read Extended info
                my $ladr=0x57;   # Last EEPROM address
                $ladr=0x56 if ( $con_bus==$gnu_i2c->{pri_bus} );
                $ladr=0x56 if exists $rev_info{substr($bus->{bus_addr},0,2)} and 
                                     $rev_info{substr($bus->{bus_addr},0,2)} == 1;
                i2c_read( $ladr, 2, 0x7f00, \$reg, 0, "x 64" );
                %info = xunpack( $reg, $einfo, \$size );

                # Print Status
                printf( "%-5s FW %02d.%02d.%04d-%03x ", $bus->{bus_name},
                        $status{fw_ver_major},$status{fw_ver_minor},$status{fw_ver_subminor},$status{makesn} );
                printf( "GUID=$info{GUID} " ); 
                printf( "BSN=%s\n", $info{BSN} );

                # now gather status info for a sanity check at the end
                # we assume the "bus name" looks like `L2CH'
                my ($blade, $device) = $bus->{bus_name} =~ m/^(..)(..)/;

                $STAT->{$blade}->{$device}->{FW} =
                        sprintf ("%02d.%02d.%04d-%03x",
                                    $status{fw_ver_major},
                                    $status{fw_ver_minor},
                                    $status{fw_ver_subminor},
                                    $status{makesn});
                $STAT->{$blade}->{$device}->{GUID} = $info{GUID};
                $STAT->{$blade}->{$device}->{BSN} = $info{BSN};
                
        }

        if( $dev =~ /eep_binfo/ ) {
                # Blade Info EEPROM

                # Switch to current bus
                return -1 if i2c_sw( $bus->{bus_addr} );

                # Read info
                return -1 if i2c_read( $bus->{$dev}->{dev_addr}, 2, 0x00, \$reg, 0, "x 64" );

                %info = xunpack( $reg, $binfo, \$size );

                printf( "%-5s Blade EEP: ver=%d BSN=%s\n", $bus->{bus_name}, $info{ver}, $info{BSN} );
                printf("\n");

                # now gather status info for a sanity check at the end
                # we assume the "bus name" looks like `L2CH'
                my ($blade, $device) = $bus->{bus_name} =~ m/^(..)(..)/;

                $STAT->{$blade}->{$device}->{VER} = $info{ver};
                $STAT->{$blade}->{$device}->{BSN} = $info{BSN};
                
        }

}


#------------------------------------------------------------------
#                            burn
#------------------------------------------------------------------
# Descr: burn devices
# Input: device type to burn, Buses to burn
# Retrn:
#------------------------------------------------------------------
sub burn {

        my $dev_type = shift @_;
        my $buses    = shift @_;

        # Check image file
        return -1 if(  !$config{bi}->{val} and check_image_file() );

        follow_bus( $con_bus, 0, "CONNECT,PAT_HOOK", 0, \&burn_dev );
}

sub burn_dev {

        my $bus = shift @_;
        my $level = shift @_;
        my $dev = shift @_;

        my $burn_cmd;
        my $rc;
        my $data;
        my $size;
        my $retry=0;

        # Prepare image name
        my $image = $config{image}->{val};
        $image .= $bus->{$dev}->{image_suffix} if exists $bus->{$dev}->{image_suffix};

        if( $dev =~ /anafa/ and $image ) {
                #
                # Burn Anafa
                #

                # Switch to current bus
                return -1 if i2c_sw( $bus->{bus_addr} );

                xtrace( 'B', 4, "Burning $dev on bus $bus->{bus_name}\n" );

                # Prepare BSN option
                my $bsn_option = "";
                if( $config{bsn}->{val} ){
                        $bsn_option = "-bsn $config{bsn}->{val}";
                        $bsn_option .= "$bus->{$dev}->{bsn_suffix}" if exists $bus->{$dev}->{bsn_suffix};
                }
                # Prepare GUID option
                my $guid_option = "";
                if( $config{guid}->{val} ){
                        $guid_option = "-guid $config{guid}->{val}";
                        $guid_option .= "$bus->{$dev}->{guid_suffix}" if exists $bus->{$dev}->{guid_suffix};
                }

                # Burn device
                $burn_cmd = "$config{emt}->{val} $image -bm $config{mst_dev}->{val} $bsn_option $guid_option";
                xtrace( 'B', 7, "Execute [$burn_cmd]\n" );

                while( $retry < $config{retry}->{val} ){
                        $rc = system( $burn_cmd );
                        if( $rc ){
                                xwarn( 4, "Burninig of $dev on $bus->{bus_name} failed retry $retry\n" );
                                last if( ($rc & 0x7F) == 2 );  # If exit by Ctrl-C no retryes
                                $retry++;
                        }
                        else {
                                xtrace( 'OK', 1, "[BURN $bus->{bus_name} PASSED OK]\n" );
                                print "\n";
                                return 0;
                        }
                }
                xtrace( 'FAILED', 4, "[BURN $bus->{bus_name} FAILED]\n" );
                print "\n";
                return -2;
        }

        if( $dev =~ /eep_binfo/ and $config{bsn}->{val} and $config{bi}->{val} ) {
                #
                # Burn blade info
                #

                # Switch to current bus
                return -1 if i2c_sw( $bus->{bus_addr} );

                xtrace( 'B', 4, "Burning $dev on bus $bus->{bus_name}\n" );

                $binfo->[$binfo_st->{BSN}]->{val} = $config{bsn}->{val};
                $binfo->[$binfo_st->{ver}]->{val} = $config{bv}->{val};
                $data = xpack( $binfo, \$size );

                $rc = i2c_write( $bus->{$dev}->{dev_addr}, 2, 0, $data, "x $size" );
                if( $rc==0 ){
                        xtrace( 'OK', 1, "[BURN $bus->{bus_name} PASSED OK]\n" );
                }
                else{
                        xerror( 4, "[BURN $bus->{bus_name} FAILED]\n" );
                }
                print "\n";
                return 0;
        }
        return 0;
}


###------------------------------------------------------------------
###                            START
###------------------------------------------------------------------
parse_cmd_line();

# Print Topology
print_topology() if( $config{T}->{val} );

#
# Get Connection Point
#
$con_bus = get_connect_point( $con_bus );
exit -2 if( ! $con_bus );
print "Connected to bus $con_bus->{bus_name}\n";

# Check BSN or GUID burning is ok
if( (($config{bsn}->{val}) or ($config{bi}->{val}) or ($config{guid}->{val})) and 
    (how_many_blades("(dev_anafa|dev_eep_binfo)")>1)){
        xwarn( 2, "Disabled GUID and/or BSN to prevent burning same values\n" );
        $config{bsn}->{val} = 0;
        $config{guid}->{val} = 0;
}

if( $con_bus==$gazelle_i2c->{pri_bus} ){
         # Disconnect Management Segemtn3,4
        xtrace( "x", 4,  "Disconnecting HUB Seg3,4 to prevent collisions\n" );
        exit -3 if( i2c_write( 0x26, 1, 7, 0x3F ));     # Set direction         
        exit -3 if( i2c_write( 0x26, 1, 3, 0x40 ));     # Disconnect Seg4         

        # Read Present Status
        exit -3 if( i2c_read( 0x20, 1, 0, \$present_leaf ));     # Read Leaf Preset Status
        xtrace( "x", 3, "Present Leaf $present_leaf\n" );
        $present_leaf = hex($present_leaf);
        exit -3 if( i2c_read( 0x20, 1, 1, \$present_spine ));    # Read Spine Preset Status
        xtrace( "x", 3, "Present Spine $present_spine\n" );
        $present_spine = hex($present_spine) | 0xC0;

        # Fill present info
        for( my $i=1; $i<=8; $i++ ){
           $present{"L$i"}=1 unless( $present_leaf & (1<<($i-1)));
        }
        for( my $i=1; $i<=8; $i++ ){
           $present{"S$i"}=1 unless( $present_spine & (1<<($i-1)) );
        }
        
        exit -3 if( i2c_write( 0x26, 1, 3, 0x00 ));     # Disconnect Seg3         

        # Read Blade info to found out revision number
        my $reg;
        foreach my $b (sort keys( %present )) {
           exit -1 if i2c_sw( $b . "CH" );    # Switch to Chassis Bus of board
           exit -1 if i2c_read( 0x53, 2, 0x00, \$reg, 0, "x 2" ); # Read info
           $reg =~ s/(..)(..)/$2$1/;
           $rev_info{$b} = hex( $reg );
        }

        print "Present Boards: ";
        foreach (sort keys( %present )) {
           print "$_(v$rev_info{$_}) ";
        }
        print "\n";

}

###
### Operations
###

# burn
if( $config{burn}->{val} or $config{bi}->{val} ) {
        burn( $con_bus );
}

# Status report
if( $config{status}->{val} ) {
        status_report();
}

#------------------------------------------------------------------
#                       Gazelle I2C access Methods
#------------------------------------------------------------------

# Check if connected to Gazelle primary bus
sub gazelle_is_prim_i2c_bus_con {

        xtrace( 'G', 3,"Checking connection to $_[0]->{bus_name}\n" );
        return !i2c_read( 0x70, 0, 0, 0, 1 );
}

sub gazelle_is_sec_i2c_bus_con {
        my $bus = shift @_;     # input - bus pointer
        my $probe = shift @_||"PROBE";

        xtrace( 'G', 3,"Checking connection to $bus->{bus_name}\n" );

        if( $con_bus == $gazelle_i2c->{pri_bus} ){
                # Check present  
                return 0 unless exists $present{ substr($bus->{bus_addr},0,2) };  
                # Try to iswitch to desired bus
                return 0 if i2c_sw( $bus->{bus_addr}, $probe );
                return 1;
        }
        else {
                # This is first time connection. Connection point is unknown
                # Try to read switch status
                return 0 if i2c_read( 0x77, 0, 0, 0, 1 );
                return 1;
        }
}

#------------------------------------------------------------------
#                       GNU I2C access Methods
#------------------------------------------------------------------

# Check if connected to Gazelle primary bus
sub gnu_is_prim_i2c_bus_con {

        xtrace( 'G', 3,"Checking connection to $_[0]->{bus_name}\n" );
        return !i2c_read( $device->{pri_bus}->{dev_i2c_sw}->{dev_addr}, 0, 0, 0, 1 );
}


#------------------------------------------------------------------
#                            i2c_read
#------------------------------------------------------------------
# Descr: read from i2c
# Input: i2c address
#        address width
#        address inside device
#        read data pointer
#        mode of probing
#        size in format "d <num> or "x <num>"
# Retrn: return 0-0k else error
#------------------------------------------------------------------
sub i2c_read {
        my $i2c_addr    = shift @_;     # i2c address
        my $addr_width  = shift @_;     # address width
        my $addr        = shift @_;     # address inside device
        my $data        = shift @_;     # read data pointer
        my $probe       = shift @_||0;  # mode of probing
        my $size        = shift @_||0;  # size in format "d <num> or "x <num>"

        my $size_opt = "";
        $size_opt = "-$size" if $size;

        # Do read
        my $cmd = sprintf( "i2c -a $addr_width $size_opt $config{mst_dev}->{val} r 0x%x 0x%x", $i2c_addr, $addr );
        xtrace( 'I', 7, "execute[$cmd]\n" );
        my $ret = qx/$cmd/;

        # Check status
        if( $? ){
                if( ! $probe ){
                        xerror( 3, "I2C read failed i2c_addr:%x(w=%d) addr:%x\n", $i2c_addr, $addr_width, $addr );
                        print "$ret\n";
                }
                return $?;
        }
        else {
                chomp( $ret );
                if($data){
                        !$size=~/^x/  ?  $$data = hex($ret) : $$data = $ret;
                }
                xtrace( 'I', 5, "Read i2c_addr:%x(w=%d) addr:%x Got data=[$ret]\n",
                                                        $i2c_addr, $addr_width, $addr, $ret );
                return 0;
        }
}

#------------------------------------------------------------------
#                            i2c_write
#------------------------------------------------------------------
# Descr: write to i2c
# Input: i2c address
#        address width
#        address inside device
#        data pointer
#        size in format "d <num> or "x <num>"
# Retrn: return 0-0k else error
#------------------------------------------------------------------
sub i2c_write {
        my $i2c_addr    = shift @_;     # i2c address
        my $addr_width  = shift @_;     # address width
        my $addr        = shift @_;     # address inside device
        my $data        = shift @_;     # data to write
        my $size        = shift @_||0;  # size in format "d <num> or "x <num>"

        my $size_opt = "";
        $size_opt = "-$size" if $size;

        my $cmd = sprintf( "i2c -a $addr_width $size_opt $config{mst_dev}->{val} w 0x%x 0x%x ", $i2c_addr, $addr );
        $size ? ($cmd .= $data) : ($cmd .= sprintf("0x%x", $data ));
        xtrace( 'I', 7, "execute[$cmd]\n" );

        # Do write
        my $ret = qx/$cmd/;

        # Check status
        if( $? ){
                xerror( 3, "I2C write failed i2c_addr:%x(w=%d) addr:%x\n", $i2c_addr, $addr_width, $addr );
                        print "$ret\n";
                return $?;
        }
        else {
                xtrace( 'I', 5, "Write i2c_addr:%x(w=%d) addr:%x done\n",
                                                        $i2c_addr, $addr_width, $addr );
                return 0;
        }
}

# retirn 0-ok, else error
sub i2c_sw {
        my $target      = shift @_;
        my $probe       = shift @_ || 0;

        my $options = "";

        # Check GNU
        if( $device == $gnu_i2c ){
                $options .= "-gnu";
        }

        # if connected to leaf or spine need to pass -leaf or -spine to isw
        if( $con_bus->{bus_name} =~/(leaf|spine)/i ){
                $options .= ("-" . lc($1)) if $con_bus->{bus_name} =~/(leaf|spine)/i;
                $target =~ s/^(L|S)\d+//;       # Remove (all like L11 or S1) from target
        }

        # Do switching
        my $cmd = sprintf( "isw $options $config{mst_dev}->{val} $target" );
        xtrace( 'I', 7, "execute[$cmd]\n" );
        my $ret = qx/$cmd/;

        # Check status
        if( $? ){
                if( ! $probe ){
                        xerror( 3, "ISW failed to reach $target\n" );
                        print "$ret\n";
                }
                xtrace( 'I', 5, "Switching to $target Failed\n" );
                return $?;
        }
        else {
                xtrace( 'I', 5, "Switched to $target\n" );
                return 0;
        }
}


#------------------------------------------------------------------
#                            parse_cmd_line
#------------------------------------------------------------------
# Descr:
# Input:
# Retrn:
#------------------------------------------------------------------
sub parse_cmd_line {

        ###
        ### Parse command line
        ###
        Getopt::Long::Configure( qw/no_ignore_case/ );
        GetOptions(     'hw=s'          => \$config{hw}->{val},
                        'c'             => \$config{c}->{val},
                        'T'             => \$config{T}->{val},
                        'help|h'        => \$config{help}->{val},
                        'man'           => \$config{man}->{val},
                        'd|dev=s'       => \$config{mst_dev}->{val},
                        'b|burn'        => \$config{burn}->{val},
                        't|trace=s'     => \$config{trace}->{val},
                        'help-trace'    => \$config{help_trace}->{val},
                        'no-color'      => \$config{no_color}->{val},
                        'i|image=s'     => \$config{image}->{val},
                        'emt=s'         => \$config{emt}->{val},
                        'bsn=s'         => \$config{bsn}->{val},
                        'guid=s'        => \$config{guid}->{val},
                        'v|ver'         => \$config{ver}->{val},
                        's|stat'        => \$config{status}->{val},
                        'bi'            => \$config{bi}->{val},
                        'r|retry'       => \$config{retry}->{val},
                        'p=s'           => \$config{pat}->{val},
                        'leaf'          => \$config{leaf_con}->{val},
                        'spine'         => \$config{spine_con}->{val},
                        'bv=s'          => \$config{bv}->{val},  
                );

        # Print Help
        pod2usage(0) if( $config{help}->{val} );
        pod2usage(1) if( $config{man}->{val} );

        # Print Version
        print "$my_version\n" and exit 0  if $config{ver}->{val};

        # Xtrace init
        xtrace_config($config{trace}->{val}, $config{no_color}->{val} );

        # Xtrace report
        xtrace_report() if $config{help_trace}->{val};

        # Print current configuration
        if( $config{c}->{val} ){
                print "Configuration Report\n";
                print "--------------------\n";
                foreach ( keys %config ){
                        printf( "   %-20s : $config{$_}->{val}\n", $config{$_}->{descr} ) if $config{$_}->{descr};
                }
        }

        # Take hw device from configuration
        $device = eval "\$$config{hw}->{val}";
        if( ! $device ){
                xerror( 1, "Unknown device type \"$config{hw}->{val}\"\n" );
                exit -2;
        }

        # Check mst device
        if( ! -e $config{mst_dev}->{val} ) {
                xerror( 1, "MST Device \"%s\" not present\n", $config{mst_dev}->{val});
                exit -3;
        }


        # Convert and Check pattern
        $op_pat = $config{pat}->{val};
        $op_pat =~ s/\*/\.\*/g;
        $op_pat =~ s/\?/\./g;
        if( ! (eval { "" =~ /$op_pat/; 1 } || 0 ) ) {
                xerror( 2, "Bus pattern \"$config{pat}->{val}\"is not valid ($op_pat)\n" );
                exit -4;
        }

        # Leaf/Spine forced
        if( $device == $gazelle_i2c ){
                if( $config{leaf_con}->{val} ){
                        $con_bus=$device->{pri_bus}->{dev_i2c_sw0}->{bus8};
                        xwarn( 1, "Connection forced to $con_bus->{bus_name}\n" ); 
                }
                if( $config{spine_con}->{val} ){
                        $con_bus=$device->{pri_bus}->{dev_i2c_sw1}->{bus8};
                        xwarn( 1, "Connection forced to $con_bus->{bus_name}\n" ); 
                }
        }
}

# check image file
sub check_image_file {
        if( ! $config{image}->{val} or ! -r $config{image}->{val} )
        {
                xwarn( 2, "Image file \"%s\" not found\n" );
                return -1;
        }
        return 0;
}

# check how many blades match bus+device pattern
sub how_many_blades {
        my $dev_pt = shift @_;

        my $match_cntr = 0;
        my $blades = {};

        if( $device == $gnu_i2c ){
           $match_cntr+=1 if "A1A2A3A4" =~ $op_pat;
           $match_cntr+=1 if "A5" =~ $op_pat;
           $match_cntr+=1 if "A6" =~ $op_pat;
           xtrace( 'x', 2, "how_many_blades: $op_pat is $match_cntr\n" );
           return $match_cntr;
        }

        follow_bus( $con_bus, 0, "PAT_HOOK", 0,
                sub{    # Check device name match
                        return 0 unless( $_[2] =~ $dev_pt );              
                        # Mark blade. Blade is 2 first characters of bus_address 
                        $blades->{substr(($_[0]->{bus_addr}),0,2)}= 'v';  
                        return 0;
                });

        $match_cntr = keys( %{$blades} );

        xtrace( 'x', 2, "how_many_blades: $dev_pt is $match_cntr\n" );
        return $match_cntr;
}

#------------------------------------------------------------------
#                            xunpack
#------------------------------------------------------------------
# Descr: unpack hex dump string to structure
# Input: hex dump string
#        pointer to hash describing structure
#        pointer to return total size
# Retrn: hash ( name=>value )
# NOTE : works in LE mode
#------------------------------------------------------------------
sub xunpack {
        my $hstr        = shift @_;     # hex dump string
        my $struct      = shift @_;     # pointer to array describing structure
        my $p_size      = shift @_;

        my %ret = ();
        my $size;

        $$p_size=0;

        foreach my $elem ( @{$struct}) {

                # STR[<size>]
                if( $elem->{type} =~ /^STR\[(\d+)\]/ ){
                        $size = $1;
                        $ret{$elem->{name}} = pack( "H" . ($size*2), $hstr );
                        $ret{$elem->{name}} =~ s/\W+//g;        # remove non printable characters

                        $hstr = substr( $hstr, $size*2 );
                        $$p_size += $size;
                }

                # UINT16
                elsif( $elem->{type} eq "UINT16" ){
                        $ret{$elem->{name}} = hex( substr($hstr,0,2) ) + (hex( substr($hstr,2,2) )<<8);

                        $hstr = substr( $hstr, 4 );
                        $$p_size += 2;
                }

                # UINT32
                elsif( $elem->{type} eq "UINT32" ){
                        $ret{$elem->{name}} =
                                hex( substr($hstr,0,2) )      +(hex( substr($hstr,2,2) )<<8)+
                               (hex( substr($hstr,4,2) )<<16) +(hex( substr($hstr,6,2) )<<24);

                        $hstr = substr( $hstr, 8 );
                        $$p_size += 4;
                }

                # HEX[<size>]
                elsif( $elem->{type} =~ /HEX\[(\d+)\]/ ){
                        $size = $1;
                        $ret{$elem->{name}} = substr( $hstr, 0, $size*2 );
                        $hstr = substr( $hstr, $size*2 );
                        $$p_size += $size;
                }

                # RESERVED[<size>]
                elsif( $elem->{type} =~ /RESERVED\[(\d+)\]/ ){
                        $size = $1;
                        $hstr = substr( $hstr, $size*2 );
                        $$p_size += $size;
                }
        }
        return %ret;
}

#------------------------------------------------------------------
#                            xpack
#------------------------------------------------------------------
# Descr: pack structure to hexdump string
# Input: pointer to hash describing structure
#        pointer to return total size
# Retrn: resulting hex string
# NOTE : works in LE mode
#------------------------------------------------------------------
sub xpack {
        my $struct      = shift @_;     # pointer to array describing structure
        my $size_p      = shift @_;     # pointer to return total size

        my $hstr = "";
        my $size;

        $$size_p = 0;

        foreach my $elem ( @{$struct} ) {

                # STR[<size>]
                if( $elem->{type} =~ /^STR\[(\d+)\]/ ){
                        $size = $1;
                        $hstr .= unpack( "H" . ($size * 2), substr( $elem->{val}." "x$size, 0, $size));
                        $$size_p += $size;
                }

                # UINT16
                elsif( $elem->{type} eq "UINT16" ){
                        $hstr .= sprintf( "%02x%02x", ($elem->{val} & 0xFF), (($elem->{val}>>8) & 0xFF) );
                        $$size_p += 2;
                }

                # UINT32
                elsif( $elem->{type} eq "UINT32" ){
                        $hstr .= sprintf( "%02x%02x%02x%02x",
                                        ($elem->{val} & 0xFF),      (($elem->{val}>>8) & 0xFF),
                                        (($elem->{val}>>16) & 0xFF),(($elem->{val}>>24) & 0xFF) );
                        $$size_p += 4;
                }

                # RESERVED[<size>]
                elsif( $elem->{type} =~ /RESERVED\[(\d+)\]/ ){
                        $size = $1;
                        $hstr .= ("0" x ($size*2));
                        $$size_p += $size;
                }
        }
        return $hstr;
}

#------------------------------------------------------------------
#                            Usage
#------------------------------------------------------------------

sub pod2usage {
        my $man = shift;
print <<'EOM';
NAME
       gz_burn
SYNOPSIS
       gz_burn [OPTIONS] gz_burn -h|--help
DESCRIPTION
       Gazelle/Gnu Burn Tool
OPTIONS
       --hw
	   select HW Device Type.  Supported devices are:
	   gazelle_i2c, gnu_i2c.  Default device is gazelle_i2c
       -d|--dev
	   Select MST device to access HW boards Default mst
	   device is /dev/mst/devasys_usb
       --emt
	   Specify command to run burn tool. Default is 'eburn'
       -h|--help|--man
	   Get help message, Get extended MAN like help message
       
        Bus/Device Selection

       -p  Specify bus selcetion pattern

        Operations

       -b|--burn
	   Command to perform Burn Operation
       -s|--stat
	   Print status report
       --bi
	   Burn blade info eeprom on chassis bus

       Additional Parameters

       -i|--image
	   Specify Image to burn. For gazelle it must be file
	   name.  For Gnu it must be directory name containing
	   images.
       --bsn
	   Specify BSN base. By default bsn is not programmed.
       --guid
	   Specify GUID base for blade. By default GUID is not
	   programmed.
       --bv
	   Specify Blade Info Version.
       --leaf|--spine
	   Force gz_burn work over leaf/spine only

       To get information about additional options run gz_burn
       --man
EOM

print <<'EOM' if ($man);

OTHER_OPTIONS
       -v|--ver
	   Print version and exit
       -c  Print configuration report
       -r|retry
	   Number of retries for burning and other operations
       --no-color
	   Do not use color in output

DESCRIPTION
       gz_burn allows you to get status or burn specific devices
       on gazelle I2c Management Bus.  In general command line
       options provided to gz_burn must define desired opera-
       tion(s), bus(es) on which this operation should be per-
       formed and additional parameters for operation.

       Following operations can be requested. They are listed in
       the same order as gz_burn will perform if more then one
       operation is requested

	burn		-b|--burn
	get status	-s|--stat	This is default operation

       gz_burn can be run on subset of gazelle I2c buses.  Cur-
       rently supported I2c buses are

	S[1..4]A[1..3]	Anafa on Spines	       ( Example S1A2 )
	S[1..4]CH	Chassis Bus on spines  ( Example S2CH )
	L[1..8]A[1..7]	Anafa on Leafs	       ( Example L2A4 )
	L[1..8]CH	Chassis Bus on leafs   ( Example L7CH )

       To select bus(es) on which you want to perform operation
       you can specify perl/grep like pattern by -p option.  By
       default pattern is '*' which means all buses.  S* is all
       spines, L* is all leafs, L*CH is chassis bus for all leafs
       e.t.c. You can see more reference info in EXAMPLES sec-
       tion.

EXAMPLES
       "gz_burn -b -i=gazelle.eeprom" - Burn all anafa in gazelle
       with image from file gazelle.eeprom
       "gz_burn -s" - Get full Gazelle status
       "gz_burn -b -p *CH -s" - Get status of all chassis bus
       "gz_burn -b -p L2A* -i=gazelle.eeprom" - Burn anafa
       devices on Leaf 2

AUTHOR
       Alex Kholodenko <xol@mellanox.co.il>.

EOM


    exit $man;
}
