#! /bin/bash

# Default values
enable_ap=0

# Override default values with networking configuration
source /etc/vega/config/fl5/vega-networking.config

#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

# make sure there is an "interface=" in the dnsmasq.conf file or the conditional editing below based on uap0 status will not work
sed -zi '/interface=/!i\
interface=lo  # This line was added by VEGA-NETSTART because no interface setting was found in the file.
' /etc/dnsmasq.conf

#Add uap0 interface (this is dependent on the wireless interface being called wlan0, which it may not be in Stretch)
if [ $enable_ap -ne 0 ];
then
  echo "VEGA-NETSTART: Adding uap0 interface" | systemd-cat
  iw dev wlan0 interface add uap0 type __ap
  sed -i '/interface=/c\interface=lo,uap0 # This line is modified by VEGA-NETSTART to add uap0 when uap0 wifi access point is enabled in the UI' /etc/dnsmasq.conf 
else
  sed -i '/interface=/c\interface=lo # This line is modified by VEGA-NETSTART to remove uap0 when uap0 wifi access point is disabled in the UI' /etc/dnsmasq.conf
fi

#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
if [ $enable_ap -ne 0 ];
then
  iptables -A FORWARD -i wlan0 -o uap0 -m state --state RELATED,ESTABLISHED -j ACCEPT
  iptables -A FORWARD -i uap0 -o wlan0 -j ACCEPT
fi
#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
if [ $enable_ap -ne 0 ];
then
  ifconfig uap0 up
fi

# Start hostapd. 10-second sleep avoids some race condition, apparently. It may not need to be that long. (?) 
if [ $enable_ap -ne 0 ];
then
  echo "VEGA-NETSTART: Starting hostapd service" | systemd-cat
  systemctl start hostapd.service
  sleep 10
fi

#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
