"""
    Firmware Checksum Calculation for FC1307 Chip

    This Python file contains the algorithm used to calculate the checksum of
    firmware for devices based on the FC1307 chip. The algorithm ensures the
    integrity and authenticity of the firmware by generating a checksum that
    can be used to verify the firmware data.

    Created by: github.com/amnemonic
    Date: 2024-05-28
"""

import sys
import glob

def calc_chcksum(bin_content):
    if len(bin_content)!=0x4000:
        return None

    chcecksum=0
    for offset in range(0,len(bin_content)-2,2):
        chcecksum = (chcecksum + int.from_bytes(bin_content[offset:offset+2],byteorder='little') ) & 0xFFFF
    
    return (0x10000 - chcecksum) & 0xFFFF, int.from_bytes(bin_content[-2:],byteorder='little')


def check_checksum(chsm_calc, chsm_stored):
    if chsm_calc==chsm_stored:
        print('     Checksum OK = 0x{:04X}'.format(chsm_calc))
    else:
        print('     Wrong checksum! Stored = 0x{:04X}, Calculated = 0x{:04X}'.format(chsm_stored,chsm_calc))



def show_info(file_name):
    bin = open(file_name,'rb').read()
    print(file_name)
    print('  == Section 0x0000 - 0x3FFF ==')
    chsm_calc, chsm_stored = calc_chcksum(bin[0x0000:0x4000])
    check_checksum(chsm_calc, chsm_stored)

    print('  == Section 0x4000 - 0x7FFF ==')
    chsm_calc, chsm_stored = calc_chcksum(bin[0x4000:0x8000])
    check_checksum(chsm_calc, chsm_stored)
    
    print('  == Section 0x8000 - 0xBFFF ==')
    chsm_calc, chsm_stored =  calc_chcksum(bin[0x8000:0xC000])
    check_checksum(chsm_calc, chsm_stored)
    
    print('  == Section 0xC000 - 0xFFFF ==')
    chsm_calc, chsm_stored = calc_chcksum(bin[0xC000:0x10000])
    check_checksum(chsm_calc, chsm_stored)

    print('')



if __name__=='__main__':
    if len(sys.argv)==2:
        show_info(sys.argv[1])
    else:
        for f in glob.glob('*.bin'):
            show_info(f)
    
