#/usr/bin/env python
#pad out a reboot.bin image and put the mac address in

import sys, string, struct

#redboot image must be 256K, since you can only flash in 256k blocks
REDBOOT_LEN = 256 * 1024

#the "Sercomm trailer" lives in the last 80 bytes.
#the only important thing is the mac address, which is at the start of this
#other bits are apparently for some windows tool
MAC_START_OFFSET = (REDBOOT_LEN - 80)

def zeros(l):
    buf = struct.pack('B', 0)
    for r in range(l):
        buf += struct.pack('B', 0)
    return buf

if (not len(sys.argv) == 4):
    print "Usage: padreboot.py input.bin m:a:c:a:d:r output.bin"
    sys.exit(1)

# sanity check and pack the mac address
mac = sys.argv[2].split(":")
if (len(mac) != 6):
    print "Invalid MAC!"
    sys.exit(1)
for i in range(len(mac)):
    mac[i] = string.atoi(mac[i], 16)
    if (mac[i] < 0 or mac[i] > 0xFF):
        print "Invalid MAC!"
        sys.exit(1)
mac_struct = struct.pack('<BBBBBB', mac[0], mac[1], mac[2], mac[3], mac[4], mac[5])

try:
    in_file = open(sys.argv[1], 'rb')
    out_file = open(sys.argv[3], 'wb')
except IOError, e:
    print e
    sys.exit(1)


binary = in_file.read()
padding = REDBOOT_LEN - len(binary) - 1
print "Input is %d bytes, padding %d" % (len(binary)-1,  padding)
binary += zeros(padding)

#write first part of binary
out_file.write(binary[:MAC_START_OFFSET])
out_file.write(mac_struct)
out_file.write(binary[MAC_START_OFFSET+6:])

