-- Per-device L2/misc long-tail sections: tunnels, stopped_rules, proxy_arp,
-- proxy_ndp, arp_rules, maclist. Each is owned by a device.

CREATE TABLE tunnels (
    id            BIGINT GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
    device        TEXT NOT NULL REFERENCES devices(name) ON DELETE CASCADE,
    type          TEXT NOT NULL,
    zone          TEXT NOT NULL,
    gateways      JSONB NOT NULL DEFAULT '[]'::jsonb,
    gateway_zones JSONB NOT NULL DEFAULT '[]'::jsonb,
    port          INT NOT NULL DEFAULT 0,
    comment       TEXT NOT NULL DEFAULT ''
);

CREATE TABLE stopped_rules (
    id      BIGINT GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
    device  TEXT NOT NULL REFERENCES devices(name) ON DELETE CASCADE,
    action  TEXT NOT NULL,
    source  TEXT NOT NULL DEFAULT '',
    dest    TEXT NOT NULL DEFAULT '',
    proto   TEXT NOT NULL DEFAULT '',
    dport   JSONB NOT NULL DEFAULT '[]'::jsonb,
    sport   JSONB NOT NULL DEFAULT '[]'::jsonb,
    comment TEXT NOT NULL DEFAULT ''
);

CREATE TABLE proxy_arp (
    id         BIGINT GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
    device     TEXT NOT NULL REFERENCES devices(name) ON DELETE CASCADE,
    address    TEXT NOT NULL,
    interface  TEXT NOT NULL DEFAULT '',
    external   TEXT NOT NULL,
    haveroute  BOOLEAN NOT NULL DEFAULT false,
    persistent BOOLEAN NOT NULL DEFAULT false,
    comment    TEXT NOT NULL DEFAULT ''
);

CREATE TABLE proxy_ndp (
    id         BIGINT GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
    device     TEXT NOT NULL REFERENCES devices(name) ON DELETE CASCADE,
    address    TEXT NOT NULL,
    interface  TEXT NOT NULL DEFAULT '',
    external   TEXT NOT NULL,
    haveroute  BOOLEAN NOT NULL DEFAULT false,
    persistent BOOLEAN NOT NULL DEFAULT false,
    comment    TEXT NOT NULL DEFAULT ''
);

CREATE TABLE arp_rules (
    id             BIGINT GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
    device         TEXT NOT NULL REFERENCES devices(name) ON DELETE CASCADE,
    action         TEXT NOT NULL,
    action_address TEXT NOT NULL DEFAULT '',
    action_mac     TEXT NOT NULL DEFAULT '',
    source         TEXT NOT NULL DEFAULT '',
    dest           TEXT NOT NULL DEFAULT '',
    opcode         INT NOT NULL DEFAULT 0,
    comment        TEXT NOT NULL DEFAULT ''
);

CREATE TABLE maclist (
    id        BIGINT GENERATED ALWAYS AS IDENTITY PRIMARY KEY,
    device    TEXT NOT NULL REFERENCES devices(name) ON DELETE CASCADE,
    action    TEXT NOT NULL,
    interface TEXT NOT NULL,
    mac       TEXT NOT NULL DEFAULT '',
    addresses JSONB NOT NULL DEFAULT '[]'::jsonb,
    log       TEXT NOT NULL DEFAULT '',
    comment   TEXT NOT NULL DEFAULT ''
);
