#!@pathperl@ -w
#
# This script generates an ihex binary image and XML description
# from an srec binary image. These are used by the Deluge binary
# image dissemination service.
#
#$Id: tos-write-image.in,v 1.5 2007-04-27 05:01:25 prabal Exp $
#@author Jonathan Hui <jwhui@cs.berkeley.edu>
#
use strict;

my $MaxNameLength = 10;

if ( @ARGV == 0 ) {
  print "usage: tos-write-image [ident_flags] [exe_file]\n";
  exit 0;
}

my %ident_flags = ();
my $exe = "";
my $ihex = "";
my $objdump = "avr-objdump";
my $platform = "";

for my $arg (@ARGV) {
  if ($arg =~ /^-DIDENT_(.+)=0x(.+)$/) {
    $ident_flags{lc($1)} = uc($2);
  }
  elsif ($arg =~ /^-DIDENT_(.+)="(.+)"$/) {
    $ident_flags{lc($1)} = $2;
  }
  elsif ($arg =~ /^--ihex=(.+)$/) {
    $ihex = $1;
  }
  elsif ($arg =~ /^--exe=(.+)$/) {
    $exe = $1;
  }
  elsif ($arg =~ /^--objdump=(.+)$/) {
    $objdump = $1;
  }
  elsif ($arg =~ /^--platform=(.+)$/) {
    $platform = $1;
  }
}

my $deluge_support = "no";
# See if app has deluge included
open( EXE, "$objdump -t $exe |") or die "Cannot open exe file: $!\n";
while(<EXE>) {
  if ( /Deluge/ ) {
    $deluge_support = "yes";
  }
}
close(EXE);
$ident_flags{"deluge_support"} = $deluge_support;
$ident_flags{"platform"} = $platform;

open ( IHEX, $ihex ) or die "Cannot open ihex file: $!\n";

print "<tos_image>\n";
print "  <ident>\n";
for my $flag (keys %ident_flags) {
  print "    <$flag>$ident_flags{$flag}</$flag>\n";
}
print "  </ident>\n";
print "  <image format=\"ihex\">\n";

while ( my $line = <IHEX> ) {
  print $line;
}

print "  </image>\n";
print "</tos_image>\n";
