/* SPDX-License-Identifier: GPL-3.0-only */
#ifndef HTP_PACKET_BRIDGE_H
#define HTP_PACKET_BRIDGE_H

#include <stddef.h>
#include <stdint.h>

#ifdef __cplusplus
extern "C" {
#endif

#define HTP_ETHERNET_HEADER_SIZE 14U
#define HTP_MAC_SIZE 6U
#define HTP_BRIDGE_MAX_PEERS 16U

typedef struct {
    uint32_t ipv4_be;
    uint8_t mac[HTP_MAC_SIZE];
    uint64_t sequence;
    int used;
} htp_bridge_peer;

typedef struct {
    uint32_t local_ipv4_be;
    uint8_t local_mac[HTP_MAC_SIZE];
    uint8_t default_peer_mac[HTP_MAC_SIZE];
    uint64_t sequence;
    int has_default_peer;
    htp_bridge_peer peers[HTP_BRIDGE_MAX_PEERS];
} htp_packet_bridge;

typedef enum {
    HTP_BRIDGE_ERROR = -1,
    HTP_BRIDGE_IGNORED = 0,
    HTP_BRIDGE_IP_PACKET = 1,
    HTP_BRIDGE_CONTROL_REPLY = 2,
} htp_bridge_result;

void htp_packet_bridge_init(
    htp_packet_bridge *bridge,
    uint32_t local_ipv4_be,
    const uint8_t local_mac[HTP_MAC_SIZE]);

int htp_packet_bridge_ip_to_ethernet(
    htp_packet_bridge *bridge,
    const uint8_t *packet,
    size_t packet_length,
    uint8_t *frame,
    size_t frame_capacity);

int htp_packet_bridge_build_arp_request(
    const htp_packet_bridge *bridge,
    uint32_t target_ipv4_be,
    uint8_t *frame,
    size_t frame_capacity);

int htp_packet_bridge_has_peer(
    const htp_packet_bridge *bridge,
    uint32_t ipv4_be);

htp_bridge_result htp_packet_bridge_ethernet_to_ip(
    htp_packet_bridge *bridge,
    const uint8_t *frame,
    size_t frame_length,
    uint8_t *packet,
    size_t packet_capacity,
    size_t *packet_length,
    uint8_t *control_reply,
    size_t control_reply_capacity,
    size_t *control_reply_length);

#ifdef __cplusplus
}
#endif

#endif
