#!/bin/sh
set -eu

action=${1:?up or down is required}
bridge=${RUNNER_BRIDGE:-mvrbr0}
subnet=${RUNNER_SUBNET:-172.30.0.0/24}
gateway=${RUNNER_GATEWAY:-172.30.0.1}
dhcp_start=${RUNNER_DHCP_START:-172.30.0.10}
dhcp_end=${RUNNER_DHCP_END:-172.30.0.200}
pid_file=${RUNNER_DNSMASQ_PID:-/run/microvm-runner/dnsmasq.pid}

case "$action" in
up)
    mkdir -p "$(dirname "$pid_file")"
    ip link show "$bridge" >/dev/null 2>&1 || ip link add "$bridge" type bridge
    ip address show dev "$bridge" | grep -Fq "$gateway/24" || ip address add "$gateway/24" dev "$bridge"
    ip link set "$bridge" up
    sysctl -q -w net.ipv4.ip_forward=1
    iptables -t nat -C POSTROUTING -s "$subnet" -j MASQUERADE 2>/dev/null || \
        iptables -t nat -A POSTROUTING -s "$subnet" -j MASQUERADE
    dnsmasq --interface="$bridge" --bind-interfaces --except-interface=lo \
        --dhcp-range="$dhcp_start,$dhcp_end,255.255.255.0,1h" \
        --dhcp-option="option:router,$gateway" --pid-file="$pid_file"
    ;;
down)
    if test -r "$pid_file"; then
        kill "$(cat "$pid_file")" 2>/dev/null || true
        rm -f -- "$pid_file"
    fi
    iptables -t nat -D POSTROUTING -s "$subnet" -j MASQUERADE 2>/dev/null || true
    ip link delete "$bridge" 2>/dev/null || true
    ;;
*)
    echo "expected up or down" >&2
    exit 64
    ;;
esac
