#!/bin/bash

# This file is part of TorBox, an easy to use anonymizing router based on Raspberry Pi.
# Copyright (C) 2026 radio_24
# Contact: anonym@torbox.ch
#
# This program is free software: you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation, either version 3 of the License, or
# (at your option) any later version.
#
# This program is distributed in the hope that it is useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
# GNU General Public License for more details.
#
# You should have received a copy of the GNU General Public License
# along with this program. If not, see <http://www.gnu.org/licenses/>.
#
# DESCRIPTION
# This file restarts hostapd, check if the daemon is working and if not resets
# the configuration with the last working version and restarts the daemon again.
# Before hostapd is changed, you have to add the following line in the code:
# sudo cp ${HOSTAPD} ${HOSTAPD_SAV}
# This creates the backup file, which is needed by HOSTAPD_SAV.
#
# SYNTAX
# nohup ./hostapd_fallback
#
#
##### SET VARIABLES ######
#
HOSTAPD="/etc/hostapd/hostapd.conf"
HOSTAPD_SAV="/etc/hostapd/hostapd.conf.tbx"

STATICIP_WLAN1=$(ip addr show wlan1 | grep -w 192.168.42.1)
if [ -n "$STATICIP_WLAN1" ]; then
	sudo sed -i "s/^interface=wlan0/interface=wlan1/" ${HOSTAPD}
fi
sudo systemctl restart hostapd
if [ -n "$STATICIP_WLAN1" ]; then
	sleep 10
	sudo sed -i "s/^interface=wlan1/interface=wlan0/" ${HOSTAPD}
fi
sleep 5
AP_STATUS=$(sudo systemctl is-active hostapd)
sleep 5
echo $AP_STATUS
if [ $AP_STATUS = activating ] || [ $AP_STATUS = inactive ]; then
	sudo cp ${HOSTAPD_SAV} ${HOSTAPD}
	if [ -n "$STATICIP_WLAN1" ]; then
		sudo sed -i "s/^interface=wlan0/interface=wlan1/" ${HOSTAPD}
	fi
sudo systemctl restart hostapd
	if [ -n "$STATICIP_WLAN1" ]; then
		sudo sed -i "s/^interface=wlan1/interface=wlan0/" ${HOSTAPD}
	fi
fi
