import sys
import hashlib

def reassemble_iflash0_from_iflash1(needle, haystack, fragment_size=1024):
    """
    Reassemble iflash0 from fragments found in iflash1.
    
    Parameters:
    - needle: binary data representing iflash0.
    - haystack: binary data representing iflash1.
    - fragment_size: size of each fragment to compare (default is 1024 bytes).
    
    Returns:
    - A bytearray that represents the reassembled iflash0 from iflash1.
    """
    needle_len = len(needle)
    haystack_len = len(haystack)
    reassembled = bytearray(needle_len)
    
    # Precompute hash for each fragment in the haystack
    haystack_hashes = {hashlib.md5(haystack[i:i+fragment_size]).digest(): i for i in range(haystack_len - fragment_size + 1)}
    
    # Reassemble iflash0 from fragments found in iflash1
    for i in range(0, needle_len, fragment_size):
        fragment_hash = hashlib.md5(needle[i:i+fragment_size]).digest()
        if fragment_hash in haystack_hashes:
            haystack_offset = haystack_hashes[fragment_hash]
            reassembled[i:i+fragment_size] = haystack[haystack_offset:haystack_offset+fragment_size]
        else:
            print(f"Fragment from iflash0 at offset {i} not found in iflash1.")
    
    return reassembled


# Main function to load the files and call the reassemble_iflash0_from_iflash1 function
if __name__ == "__main__":
    iflash0_file = sys.argv[1]
    iflash1_file = sys.argv[2]
    output_file = "reconstructed_iflash0.bin"
    
    with open(iflash0_file, "rb") as f0:
        data_iflash0 = f0.read()

    with open(iflash1_file, "rb") as f1:
        data_iflash1 = f1.read()

    # Reassemble iflash0 from iflash1
    reassembled_data = reassemble_iflash0_from_iflash1(data_iflash0, data_iflash1)

    # Save the reassembled data to a binary file
    with open(output_file, "wb") as f_out:
        f_out.write(reassembled_data)
    
    print(f"iflash0 reassembled from iflash1 and saved to {output_file}")
