#!/bin/sh

# creates a namespace called private
sudo ip netns add private

# creates a veth pair, a veth-host int and a veth-private int
sudo ip link add veth-host type veth peer name veth-private

# move veth-private to the private ns
sudo ip link set veth-private netns private

# we need the private namespace so normal apps dont have 
# access to the LAN which is provided by the wireguard interface
# gives the host an ip address and puts its status to up
sudo ip addr add 172.20.0.1/24 dev veth-host
sudo ip link set veth-host up

# init the loopback interface on the private namespace
# then gives the veth-private int an IP address
# sets the interface status to up
sudo ip netns exec private ip link set lo up
sudo ip netns exec private ip addr add 172.20.0.2/24 dev veth-private
sudo ip netns exec private ip link set veth-private up

# setting the default route to 172.20.0.1 (veth-host on the normal namespace)
# lets the private netns communicate with the normal namespace which in 
# most cases means doing this gives it internet access which is requried in our case for the 
# wireguard int to get its handshake thru 
sudo ip netns exec private ip route add default via 172.20.0.1

# then set ip_forward to 1 (enable it) to allow both namespaces to speak to eachother 
# with their veth pairs 
sudo sysctl -w net.ipv4.ip_forward=1

# set iptable rules which lets our actual ethernet interface (or potentially wifi)
# to allow in 

HOST_INT=enp0s1

# allows packets that arrive on veth-host (traffic originating from the private namespace) 
# to be forwarded out through the real uplink interface
sudo iptables -A FORWARD -i veth-host -o $HOST_INT -j ACCEPT

# allows the HOST_INT to forward packets that are releated or established 
# (meant for veth-host) to be forwarded to veth-host 
sudo iptables -A FORWARD -i $HOST_INT -o veth-host \
    -m conntrack --ctstate RELATED,ESTABLISHED -j ACCEPT

# edits the nat iptable, when new packets are created from the 172.20.0.0/24 network
# it will edit the host ip to be the HOST_INT's ip?
sudo iptables -t nat -A POSTROUTING \
    -s 172.20.0.0/24 -o $HOST_INT  -j MASQUERADE

# creates our wireguard interface based off our config
sudo ip netns exec private wg-quick up ./wg0.conf
