#!/bin/bash
DIR="$( cd "$( dirname "${BASH_SOURCE[0]}" )" && pwd )"
cd $DIR

. basicFunctions

AP_ACTIVE="false"
writeServerConf

systemctl is-active --quiet hostapd
RET=$?
if [ $RET -eq 0 ] ; then
  service hostapd stop
  systemctl disable hostapd
fi

systemctl is-active --quiet dnsmasq
RET=$?
if [ $RET -eq 0 ] ; then
  service dnsmasq stop
  systemctl disable dnsmasq
  rm /etc/dnsmasq.d/hotspot.conf
  # Remove forwarding rule
  if [[ -f /usr/sbin/iptables ]]; then
    iptables -t nat -D  POSTROUTING -o eth0 -j MASQUERADE
    sh -c "iptables-save > /etc/iptables.ipv4.nat"
  fi
fi
echo "Updating dhcpcd ..."
updateDHCPCD


# Ensure basic config file exists
echo "Creating wpa_supplicant ..."
writeWPASupplicant

systemctl is-active --quiet  wpa_supplicant@${WLAN}
RET=$?
if [ $RET -ne 0 ] ; then
  # Start wlan
  echo "Activating services ..."
  systemctl enable wpa_supplicant@${WLAN}.service
  systemctl restart wpa_supplicant@${WLAN}.service
fi
iw $WLAN set power_save off
# sleep 1
