import sys
import os

table = {
    'blob':   (0x000a0000,131072,0x800,),
    'param':  (0x000c0000,131072,0,),
    'kernel': (0x000e0000,2097152,0,),
    'root':   (0x002e0000,64094208,0,)
}

def err(msg):
  print msg
  sys.exit(1)

def run(cmd,really=True):
  print "run %s"%cmd

  if not really:
    return

  pipe = os.popen(cmd)
  pipe.close()

def fsize(file):
  return os.stat(file).st_size

part = sys.argv[1]
file = sys.argv[2]

if not part in table:
  err('oops')

addr,size,off = table[part]

if fsize(file) > size:
  err("too long")


print "%s at %x+%x"%(part,addr,off)

print "make empty file %d len"%(size)
run("dd if=/dev/zero of=/tmp/mtd bs=1k count=%d"%(size/1024))

print "write data to file"
run("dd if=%s of=/tmp/mtd bs=1k seek=%d conv=notrunc"%(file,off/1024))

print "flash data"
run("boot_usb flash 0x%x /tmp/mtd"%addr)

print "remove file"
run("rm /tmp/mtd")

