#!/usr/bin/perl -w

use strict;

# the fields we want to find ...
my @fields = 
    qw(
       magic
       checksum
       version
       length
       systemBuilderID
       runtimeMemory
       dataSize
       dataChecksum
       compressionMethod

      
       signature
       hardwareType
       hardwareRevision
       chipType
       cpuId
       checksum
       buildVersion
       strSystem
       strRelease
       strRevision
       strDate
       strBspVersion
       strCspVersion
       );

my %types = ( 
    'systemBuilderID' => 'A15',
    'compressionMethod' => 'C',	      
    'strCspVersion' => 'A32',   
    'pad' => 'C4',
);


my %expected = (
    'magic'     => 0x496dd694,		
    'signature' => 0x41494d30
);
		
my %fldtypes = (
   'systemBuilderID' => '%s'
);

foreach my $field (@fields) {
    if ( $field =~ m/^str/ ) {
	$types{$field} = "a32" unless defined $types{$field};
	$fldtypes{$field} = "%s";
    } else {
	$types{$field} = "V" unless defined $types{$field};
	$fldtypes{$field} = "0x%x" unless defined $fldtypes{$field};
    }
}


# The template used for unpacking ....

my $template = "";
foreach my $f (@fields) {
    $template .= $types{$f};
}

my $file = shift @ARGV;

my $usage =<<EOF;
usage: $0 [-x] file
  -x - extract payload and write to stdout
EOF

die $usage, unless defined $file;

my $extract;
if ( $file eq '-x' ) {
    $extract = 1;
    $file = shift @ARGV;
}

undef $/;
open (F,$file) or die "failed to open $file:$!\n";

if ( $extract ) {
    seek(F,512,0);
    print <F>;
    exit;
}
my $contents = <F>;

my @values = unpack($template, $contents);

my %values;
my $i = 0;
foreach my $f (@fields) {
   $values{$f} = $values[$i++];
}

# Fix up chip type number
my $chiptype = $values{'chipType'};
my @chiptypes = qw( Hydrogen Helium Lithium Beryllium Augustus Claudius );

if ( defined $chiptypes[$chiptype] ) {
    $values{'chipType'} = $chiptypes[$chiptype];
    $fldtypes{'chipType'} = "%s";
}

my @compressions = qw (None LZ01 Bzip Zlib);
my $comptype = $values{'compressionMethod'};

if ( defined $compressions[$comptype] ) {
    $values{'compressionMethod'} = $compressions[$comptype];
    $fldtypes{'compressionMethod'} = "%s";
}

foreach my $f (@fields) {
    my $expected = "";
    if ( defined $expected{$f} ) {
	$expected = sprintf( " (expected %x)", $expected{$f} );
    }
    my $fldtype = $fldtypes{$f};
    die unless defined $fldtype;
    printf("%-32s: $fldtype$expected\n", $f, $values{$f} );
}



