#!/bin/bash
# Copyright 2022 The ChromiumOS Authors
# Use of this source code is governed by a BSD-style license that can be
# found in the LICENSE file.

# Set up networking on the host using a TAP device. This probably works on
# many ubuntu or debian machines, but highly depends on the existing network
# configuration.

setup_network() {
    # ANCHOR: setup_tap
    sudo ip tuntap add mode tap user "$USER" vnet_hdr crosvm_tap
    sudo ip addr add 192.168.10.1/24 dev crosvm_tap
    sudo ip link set crosvm_tap up
    # ANCHOR_END: setup_tap

    # ANCHOR: setup_routing
    sudo sysctl net.ipv4.ip_forward=1
    # Network interface used to connect to the internet.
    HOST_DEV=$(ip route get 8.8.8.8 | awk -- '{printf $5}')
    sudo iptables -t nat -A POSTROUTING -o "${HOST_DEV}" -j MASQUERADE
    sudo iptables -A FORWARD -i "${HOST_DEV}" -o crosvm_tap -m state --state RELATED,ESTABLISHED -j ACCEPT
    sudo iptables -A FORWARD -i crosvm_tap -o "${HOST_DEV}" -j ACCEPT
    # ANCHOR_END: setup_routing
}

echo "This will set up a tap device 'crosvm_tap'."
echo
echo "It will run the following commands:"
echo
type setup_network | sed '1,3d;$d'
echo
read -p "Continue [y/N]? " -r
if [[ ! $REPLY =~ ^[Yy]$ ]]; then
    exit 0
fi

set -ex
setup_network
