"""Write a synthetic pcap: SOME/IP-SD offers from two ECUs and their events, one ECU on VLAN 10."""
import math, random, struct, sys, ipaddress

def someip(service, method, payload, client=0, session=1, mtype=0x02):
    return struct.pack(">HHIHHBBBB", service, method, 8 + len(payload), client, session, 1, 1, mtype, 0) + payload

def offer(service, instance, ip, port, session):
    entry = struct.pack(">BBBBHHB", 0x01, 0, 0, 0x10, service, instance, 1) + (3).to_bytes(3, "big") + struct.pack(">I", 0)
    opt = struct.pack(">HBB4sBBH", 9, 4, 0, ipaddress.IPv4Address(ip).packed, 0, 0x11, port)
    body = bytes([0xC0, 0, 0, 0]) + struct.pack(">I", len(entry)) + entry + struct.pack(">I", len(opt)) + opt
    return someip(0xFFFF, 0x8100, body, session=session)

def ipv4_checksum(header):
    s = sum(struct.unpack(">10H", header))
    while s > 0xFFFF: s = (s & 0xFFFF) + (s >> 16)
    return ~s & 0xFFFF

def frame(src_mac, dst_mac, src_ip, dst_ip, sport, dport, payload, vlan=None):
    udp = struct.pack(">HHHH", sport, dport, 8 + len(payload), 0) + payload
    ip = struct.pack(">BBHHHBBH4s4s", 0x45, 0, 20 + len(udp), 0, 0x4000, 64, 17, 0,
                     ipaddress.IPv4Address(src_ip).packed, ipaddress.IPv4Address(dst_ip).packed)
    ip = ip[:10] + struct.pack(">H", ipv4_checksum(ip)) + ip[12:]
    eth = bytes.fromhex(dst_mac) + bytes.fromhex(src_mac)
    eth += (struct.pack(">HH", 0x8100, vlan) if vlan else b"") + struct.pack(">H", 0x0800)
    return eth + ip + udp

def build(path, seconds=20):
    random.seed(1)
    records = []
    sd_dst = "224.224.224.245"
    mcast_mac = "01005e60e0f5"
    sessions = {"a": 0, "b": 0}
    ecus = {"a": ("020000000a14", "192.168.10.20", 0x1234, 30509, None),
            "b": ("020000000a1e", "192.168.10.30", 0x2001, 30510, 10)}
    counter = 0
    for ms in range(0, seconds * 1000, 10):
        t = ms / 1000
        if ms % 1000 == 0:
            for key, (mac, ip, service, port, vlan) in ecus.items():
                sessions[key] += 1
                records.append((t, frame(mac, mcast_mac, ip, sd_dst, 30490, 30490, offer(service, 1, ip, port, sessions[key]), vlan)))
        speed = round((50 + 30 * math.sin(t / 3)) * 100)
        counter = (counter + 1) & 0xFF
        payload = struct.pack(">HBB", speed, counter, 0x01)
        records.append((t + 0.0002, frame("020000000a14", "020000000a32", "192.168.10.20", "192.168.10.50", 30509, 40001,
                                          someip(0x1234, 0x8001, payload, session=(ms // 10) % 0xFFFF + 1), None)))
        if ms % 100 == 0:
            door = 1 if 5 <= t < 9 else 0
            records.append((t + 0.0004, frame("020000000a1e", "020000000a32", "192.168.10.30", "192.168.10.50", 30510, 40002,
                                              someip(0x2001, 0x8002, bytes([door, 0x00, 0x7F, 0xFF])), 10)))
    with open(path, "wb") as f:
        f.write(struct.pack("<IHHiIII", 0xA1B2C3D4, 2, 4, 0, 0, 65535, 1))
        for t, data in sorted(records, key=lambda r: r[0]):
            sec = 1_700_000_000 + int(t)
            usec = round((t - int(t)) * 1_000_000)
            f.write(struct.pack("<IIII", sec, usec, len(data), len(data)) + data)

if __name__ == "__main__":
    build(sys.argv[1] if len(sys.argv) > 1 else "capture.pcap")
