#!/bin/bash

function daemon_stop()
{
	echo "Stopping all wlan services (if running)..."
	systemctl daemon-reload
	systemctl stop hostapd
	systemctl stop dnsmasq
}

function daemon_start()
{
	echo "Waiting for eth0 to be setup before trying to run DNSMasq"
	sleep 10
	echo "Start DNSMasq"
	systemctl start dnsmasq
}

function forwarding()
{
	echo "Enable IPV4 forwarding"
	sysctl net.ipv4.ip_forward=1
}

function iptables_clear()
{
	echo "Clear iptables (in case we play with this script from the command line)"
	iptables -F
	iptables -t nat -F
}

function iptables_router()
{
	# Allow just your own LAN
	iptables -P FORWARD DROP
	iptables -A FORWARD -i wlan0 -j ACCEPT

	# Cut off your own LAN from the wifi.
	iptables -A FORWARD -i wlan0 -d 192.168.0.0/16 -j REJECT
	iptables -A FORWARD -i wlan0 -d 10.0.0.0/24    -j REJECT

	# Route as required
	iptables -A FORWARD -i eth0 -m state --state ESTABLISHED,RELATED -j ACCEPT
	iptables -A FORWARD -i eth0 -m state --state NEW,ESTABLISHED,RELATED -j ACCEPT

	echo "Add NAT routing as we'll need this for routing between our subnets and the internet"
	iptables -t nat -A POSTROUTING -o wlan0 -j MASQUERADE
}

function iptables_list()
{
	# List the iptables
	echo "Filter"
	iptables -L -v
	echo "NAT"
	iptables -t nat -L -v
}

function iptables_config()
{
	iptables_clear
	iptables_router
	iptables_list
}

# Tidy up in case we are playing with this script
daemon_stop

# Setup the hotspot
forwarding
daemon_start
iptables_config

# Clean exit
exit 0

