#!/usr/bin/perl -w

#patches the bootloaders hex file with identification data

my $serial = $ARGV[0];

# make it 6 digits:
while( length($serial) < 6 ){
	$serial = '0' . $serial;
}

# knock or no knock
$identity = ($serial < 135 ? "v3.3_k" : "v3.3_n") . $serial; # 12 chars max

print STDERR "identity=$identity\n";

sub identity
{
	my $i = shift;
	return substr($identity, $i, 1);
}


# hmm.. no match /^:0CFFF000(\w+)/ ... $ tail boot\main.hex
#:10FF40005F926F927F928F929F92AF92BF92CF9269
#:10FF5000DF92EF92FF920F931F93CF93DF93CDB772
#:10FF6000DEB7CA1BDB0B0FB6F894DEBF0FBECDBFEA
#:10FF700009942A88398848885F846E847D848C84BB
#:10FF80009B84AA84B984C884DF80EE80FD800C81C4
#:10FF90001B81AA81B981CE0FD11D0FB6F894DEBFA7
#:08FFA0000FBECDBFED01089575
#:04FFFC000C9400FC65
#:040000031000F800F1
#:00000001FF

while(<STDIN>) {

    if (/^:0CFFF000(\w+)/) {
	my $data=$1;
	if ($data =~ /0{25}5/) { # good, array is zero'ed as expected
	    print ":0CFFF000";
	    # split string into bytes and calculate checksum
	    my $chksum = hex("0c") + hex("ff") + hex("f0"); #+ hex(00)
	    for (my $i=0; $i<12; $i++) {
		my $val = unpack("%8C*", identity($i));
		$chksum += $val;
		printf("%02X", $val);
	    }
	    $chksum = 256 - ($chksum % 256);  # sum of all hex bytes must be zero
	    $chksum = $chksum % 256;
	    printf("%02X\n", $chksum);
	} else {
	    print STDERR "ERROR: The identity array already contains data, maybe the bootloader code overlaps? Check it!\n";
	    exit -1;
	}
    } else {
	print $_;
    }
}

exit 0;
