import binascii

# Path to the input file
input_file = "/var/www/html/modification_carto/golf pcr fls full read boot foxfls.unknown"
output_file = "/var/www/html/modification_carto/golf_pcr_fls_full_read_boot_foxfls_modified.unknown"
output_log_file = "/var/www/html/modification_carto/segment_logs.txt"

# Read the file in binary mode
with open(input_file, 'rb') as file:
    file_content = bytearray(file.read())

# Convert the file content to hexadecimal
hex_content = binascii.hexlify(file_content).decode('utf-8')
first_1000_chars = hex_content[:1000]
print("First 1000 characters of the file in hex:")
print(first_1000_chars)

# Known MCUID for verification
mcuid_hex = "4104058606609011820600102403ED00"
mcuid_bytes = bytes.fromhex(mcuid_hex)

# Define segment size and calculate the number of segments
segment_size = len(mcuid_bytes)
num_segments = len(file_content) // segment_size

matching_segments = []

# Function to apply specific transformations
def apply_specific_transformations(segment, mcuid_bytes):
    transformations = []
    for i in range(len(segment)):
        original_byte = segment[i]
        mcuid_byte = mcuid_bytes[i]
        results = {
            "addition_mod": (mcuid_byte + original_byte) % 256,
            "xor": mcuid_byte ^ original_byte,
            "subtraction_mod": (mcuid_byte - original_byte) % 256
        }
        transformations.append(results)
    return transformations

# Analyze the segments
for i in range(num_segments):
    segment = file_content[i * segment_size: (i + 1) * segment_size]
    
    # Skip segments with mostly zeros
    if segment.count(0) > segment_size / 2:
        continue
    
    transformations = apply_specific_transformations(segment, mcuid_bytes)
    matching_segments.append((i, segment, transformations))

# Function to deduce MCUID and return positions
def deduce_mcuid(segment, transformations, segment_index):
    deduced_bytes = [None] * len(segment)
    positions = [None] * len(segment)
    for i, trans in enumerate(transformations):
        if trans["addition_mod"] == (mcuid_bytes[i] + segment[i]) % 256:
            deduced_bytes[i] = (trans["addition_mod"] - segment[i]) % 256
        elif trans["xor"] == (mcuid_bytes[i] ^ segment[i]):
            deduced_bytes[i] = segment[i] ^ trans["xor"]
        elif trans["subtraction_mod"] == (mcuid_byte - segment[i]) % 256:
            deduced_bytes[i] = (trans["subtraction_mod"] + segment[i]) % 256
        positions[i] = segment_index * segment_size + i
    return deduced_bytes, positions

# Process matching segments and deduce MCUID
matching_segments_info = []
for index, segment, transformations in matching_segments:
    deduced_bytes, positions = deduce_mcuid(segment, transformations, index)
    segment_info = {
        "index": index,
        "segment": segment.hex(),
        "deduced_bytes": deduced_bytes,
        "positions": positions,
        "transformations": transformations
    }
    matching_segments_info.append(segment_info)

# Verify deduced MCUID
def verify_mcuid(deduced_bytes):
    return all(byte is not None for byte in deduced_bytes)

# Modify the file content
for segment_info in matching_segments_info:
    positions = segment_info["positions"]
    for pos in positions:
        file_content[pos] = 0x58  # Replace with 'X' (0x58)

# Save the modified file
with open(output_file, 'wb') as file:
    file.write(file_content)

# Log the segments and positions to a file
with open(output_log_file, 'w') as log_file:
    log_file.write("Matching segments in the file:\n")
    for segment_info in matching_segments_info:
        index = segment_info["index"]
        segment = segment_info["segment"]
        transformations = segment_info["transformations"]
        deduced_bytes = segment_info["deduced_bytes"]
        positions = segment_info["positions"]
        log_file.write(f"Index: {index}, Segment: {segment}\n")
        for i, (orig, trans, deduced, pos) in enumerate(zip(bytearray.fromhex(segment), transformations, deduced_bytes, positions)):
            log_file.write(f"  Byte {i}: Original: {orig}, Transformations: {trans}, Deduced MCUID Byte: {deduced}, Position: {pos}\n")

    log_file.write(f"Total matching segments: {len(matching_segments_info)}\n")

print("Log saved to", output_log_file)
print("Modified file saved to", output_file)
