#!/usr/bin/env bash
# Create the host-only ``br-malware`` bridge for Tier-3+ episodes.
#
# Properties (from docs/architecture.md):
#   - Bridge address 10.200.0.1/24 on the host side.
#   - NO NAT, NO route, NO DNS — guests cannot reach the host or the
#     internet. The bridge only carries traffic between the host and
#     the guests on it.
#   - Lab-host and target VMs both attach via tap devices created by
#     the launcher.
#
# Run as root, ONCE per host. Idempotent — re-running is safe.

set -euo pipefail

BRIDGE="${BRIDGE:-br-malware}"
BRIDGE_IP="${BRIDGE_IP:-10.200.0.1/24}"

log() { printf '[setup_bridge] %s\n' "$*" >&2; }

[[ $EUID -eq 0 ]] || { log "must run as root"; exit 1; }

if ! command -v ip >/dev/null; then
    log "iproute2 (`ip`) is required"
    exit 1
fi

if ! ip link show "$BRIDGE" >/dev/null 2>&1; then
    log "creating bridge $BRIDGE"
    ip link add name "$BRIDGE" type bridge
    # Disable spanning-tree on the host-only bridge — it isn't needed
    # and adds startup delay.
    ip link set "$BRIDGE" type bridge stp_state 0
fi

ip link set "$BRIDGE" up

# Add the host-side address if not already there.
if ! ip -4 addr show dev "$BRIDGE" | grep -q "${BRIDGE_IP%%/*}"; then
    log "adding $BRIDGE_IP to $BRIDGE"
    ip addr add "$BRIDGE_IP" dev "$BRIDGE"
fi

# Make sure the kernel does NOT forward between this bridge and any
# other interface. We don't want a misconfigured net.ipv4.ip_forward
# to leak the malware bridge to the LAN.
if [[ "$(cat /proc/sys/net/ipv4/ip_forward)" == "1" ]]; then
    log "WARNING: net.ipv4.ip_forward=1 — make sure iptmonads / nftables"
    log "blocks traffic from $BRIDGE to non-loopback devices."
fi

log "bridge ready: $(ip -4 -br addr show "$BRIDGE")"
log ""
log "Launchers can now opt into tap+bridge mode by setting:"
log "  BRIDGE=$BRIDGE   (tells launch_target.sh to attach a tap to this bridge)"
log "Default launcher behaviour stays SLIRP usermode for simplicity."
