#! /bin/bash

#Make sure no uap0 interface exists (this generates an error; we could probably use an if statement to check if it exists first)
echo "VEGA-NETSTART: Removing uap0 interface" | systemd-cat
iw dev uap0 del

#Add uap0 interface (this is dependent on the wireless interface being called wlan0, which it may not be in Stretch)
echo "VEGA-NETSTART: Adding uap0 interface" | systemd-cat
iw dev wlan0 interface add uap0 type __ap

#Modify iptables (these can probably be saved using iptables-persistent if desired)
echo "VEGA-NETSTART: IPV4 forwarding: setting" | systemd-cat
#sysctl net.ipv4.ip_forward=1
#echo "net.ipv4.ip_forward=1" >> /etc/sysctl.conf
sed -i 's/^#net.ipv4.ip_forward=.*$/net.ipv4.ip_forward=1/' /etc/sysctl.conf
echo "VEGA-NETSTART: Editing IP tables"
echo 1 > /proc/sys/net/ipv4/ip_forward
iptables -F
iptables -t nat -F
sleep 2
iptables -t nat -A POSTROUTING -s 10.0.0.0/24 ! -d 10.0.0.0/24 -j MASQUERADE
iptables -t nat -A POSTROUTING -o wlan0 -j MASQUERADE
iptables -A FORWARD -i wlan0 -o uap0 -m state --state RELATED,ESTABLISHED -j ACCEPT
iptables -A FORWARD -i uap0 -o wlan0 -j ACCEPT
#iptables-save > /etc/iptables/rules.v4
iptables-save > /etc/iptables.ipv4.nat
#iptables-restore < /etc/iptables.ipv4.nat

# Bring up uap0 interface. Commented out line may be a possible alternative to using dhcpcd.conf to set up the IP address.
#ifconfig uap0 10.0.0.1 netmask 255.255.255.0 broadcast 10.0.0.255
ifconfig uap0 up

# Start hostapd. 10-second sleep avoids some race condition, apparently. It may not need to be that long. (?) 
echo "VEGA-NETSTART: Starting hostapd service" | systemd-cat
systemctl start hostapd.service
sleep 10

#Start dhcpcd. Again, a 5-second sleep
echo "VEGA-NETSTART: Starting dhcpcd service" | systemd-cat
systemctl start dhcpcd.service
sleep 20

echo "VEGA-NETSTART: Starting dnsmasq service" | systemd-cat
systemctl restart dnsmasq.service
#systemctl start dnsmasq.service

echo "VEGA-NETSTART: DONE" | systemd-cat