import shutil
import sys
import os
import json



BOOT_PATH ="JW3425_boot_v12.bin"
APP_PATH ="csmzm_app_v0.06.bin"
OUT_PATH = BOOT_PATH.split('.')[0]+APP_PATH.split('.')[0]+".jwt"

# 创建离线下载器的镜像


# 填充指定个数的byte
def arr_byte_copy(byte:int,num:int):
    t=bytearray()
    for i in range(num):
        t.append(byte)
    return t
# int转数组
def arr_from_int(num:int):
    return  bytearray([num&0xff,(num>>8)&0xff,(num>>16)&0xff,(num>>24)&0xff])


def arr_from_str(txt:str):
    t=bytearray(txt.encode(encoding="utf-8"))
    t+=arr_byte_copy(0,1)
    return t


def crc32(data:bytearray):
    temp=0
    crc=0xffffffff
    i=0
    if(len(data)%4!=0):
        return 0
    while(i<len(data)):
        temp=data[i]|(data[i+1]<<8)|(data[i+2]<<16)|(data[i+3]<<24)
        i+=4
        for j in range(32):
            if((crc^temp)&0x80000000)!=0:
                crc=0x04c11db7^(crc<<1)
            else:
                crc<<=1
            temp<<=1
        crc&=0xffffffff
    return crc



def creat():
    boot=BOOT_PATH
    app=APP_PATH
    d=bytearray()
    with open(boot,"rb") as f:
        d+=f.read()
    d+=arr_byte_copy(0x00,4096-len(d))
    with open(app,"rb") as f:
        d+=f.read()
    d+=arr_byte_copy(0x00,0x3c7c-len(d))
    d+=arr_from_int(0x55aa6699)
    d+=arr_byte_copy(0x00,1024*16-len(d))

    crc_all=crc32(d)
    crc_app=crc32(d[4096:4096+11*1024])
    print("crc32 of all data:",hex(crc_all))
    print("crc32 for 0x1000:",hex(crc_app))
    d+=arr_from_int(crc_all)
    d+=arr_from_int(crc_app)
    d+=arr_from_str(OUT_PATH)

    with open(OUT_PATH,"wb+") as f:
        f.write(d)
        print(OUT_PATH+" create boot file success.")
    
    

if __name__ == "__main__":
    
    if(len(sys.argv)>=2):

        rom_input=sys.argv[1]
        APP_PATH ="__csmzm_app.bin"
        OUT_PATH = '.'.join(rom_input.split('.')[:-1])+".jwt"
        d=bytearray()
        with open(rom_input,"rb") as f:
            d+=f.read()
        with open(APP_PATH,"wb+") as f:
            f.write(d[4096:4096+11*1024])
        creat()



