#!/bin/bash

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

function daemon_start()
{
	echo "Bring the WiFi up"
	ifconfig wlan0 up
	systemctl start hostapd

	echo "Waiting for wlan0 to be setup before trying to run DNSMasq"
	sleep 15
	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 eth0 -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 wlan0 -m state --state ESTABLISHED,RELATED -j ACCEPT
	iptables -A FORWARD -i wlan0 -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 eth0 -j MASQUERADE
}

function iptables_redirect()
{
	IPS=`ip -4 addr show | grep inet | grep -v 127.0 | sed "s@/@ @" | awk '{print $2}'`
	for IP in $IPS
	do
		echo "Allow people to use port 80 to get SeeDeclip4 at port 8000 ($IP)"
		iptables -t nat -I PREROUTING -p tcp --dport 80 -j REDIRECT -d $IP --to-ports 8000
	done
}

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_redirect
	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

