#! /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

# Clean up any persistent NAT/IP forwarding configurations from previous versions
echo "VEGA-NETSTART: Cleaning up NAT/IP forwarding configurations" | systemd-cat

# Disable IP forwarding in runtime
echo 0 > /proc/sys/net/ipv4/ip_forward

# Comment out IP forwarding in sysctl.conf to prevent it from being enabled on boot
sed -i 's/^net.ipv4.ip_forward=1/#net.ipv4.ip_forward=1/' /etc/sysctl.conf

# Clear all iptables rules
iptables -F
iptables -t nat -F

# Reset iptables chains to default policies
iptables -P INPUT ACCEPT
iptables -P FORWARD ACCEPT
iptables -P OUTPUT ACCEPT

# Remove any persistent iptables rules files
rm -f /etc/iptables.ipv4.nat
rm -f /etc/iptables/rules.v4

echo "VEGA-NETSTART: NAT/IP forwarding cleanup completed" | systemd-cat

# 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
