#!/bin/bash
################################################################################
# Copyright 2026 ModalAI Inc.
#
# Redistribution and use in source and binary forms, with or without
# modification, are permitted provided that the following conditions are met:
#
# 1. Redistributions of source code must retain the above copyright notice,
#    this list of conditions and the following disclaimer.
#
# 2. Redistributions in binary form must reproduce the above copyright notice,
#    this list of conditions and the following disclaimer in the documentation
#    and/or other materials provided with the distribution.
#
# 3. Neither the name of the copyright holder nor the names of its contributors
#    may be used to endorse or promote products derived from this software
#    without specific prior written permission.
#
# 4. The Software is used solely in conjunction with devices provided by
#    ModalAI Inc.
#
# THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS"
# AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE
# IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE
# ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER OR CONTRIBUTORS BE
# LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR
# CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF
# SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS
# INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN
# CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE)
# ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE
# POSSIBILITY OF SUCH DAMAGE.
################################################################################

# Interface variables (set by detect_wifi_interfaces)
AP_INTERFACE=""
STA_INTERFACE=""
SUPPORTS_CONCURRENT=false

#
# Detect available WiFi interfaces and concurrent capability
#
detect_ap_interface() {

	local max_wait=30
	local count=0

	echo "Detecting WiFi AP interface..."

	while [ $count -lt $max_wait ]; do

		# 1) Check for STA+AP capable interfaces (common on some chipsets)
		if [[ -d /sys/class/net/uap0 && -d /sys/class/net/mlan0 ]]; then
			AP_INTERFACE="uap0"
			STA_INTERFACE="mlan0"
			SUPPORTS_CONCURRENT=true
			echo "Detected concurrent-capable WiFi: AP=$AP_INTERFACE, STA=$STA_INTERFACE"
			return 0
		fi

		# Helper: is this interface actually wireless?
		is_wireless_if() {
			local ifn="$1"
			[[ -d "/sys/class/net/$ifn/wireless" ]] && return 0
			[[ -e "/sys/class/net/$ifn/phy80211" ]] && return 0
			return 1
		}

		# 2) Prefer wlan0 if it exists and is wireless
		if [[ -d /sys/class/net/wlan0 ]] && is_wireless_if wlan0; then
			AP_INTERFACE="wlan0"
			STA_INTERFACE="wlan0"
			echo "Detected WiFi interface: $AP_INTERFACE"
			return 0
		fi

		# 3) Otherwise pick the first "wl*" interface that is actually wireless.
		# This will catch wlx<MAC> names (and other wl* names).
		local ifn
		for ifn in $(ls /sys/class/net 2>/dev/null | sort); do
			[[ "$ifn" == wl* ]] || continue
			is_wireless_if "$ifn" || continue
			AP_INTERFACE="$ifn"
			STA_INTERFACE="$ifn"
			echo "Detected WiFi interface: $AP_INTERFACE"
			return 0
		done

		sleep 1
		((count++))

		# Show progress every 5 seconds
		if [ $((count % 5)) -eq 0 ]; then
			echo "  Still waiting for WiFi interface... ($count/$max_wait)"
		fi
	done

	# Error out after timeout
	echo "ERROR: No WiFi interface found after ${max_wait}s"
	echo "WiFi driver may not be loaded or hardware not available"
	echo "Check WiFi configuration with 'voxl-wifi getmode'"
	exit 1
}


print_usage(){
	echo ""
	echo " This file is not meant to be called directly, if you're looking to start"
	echo " start softap, please use the voxl-wifi tool from voxl-utils"
	echo ""
	echo " Starts and stops softap mode"
	echo ""
	echo ""
	echo " Usage:"
	echo ""
	echo "  ./softap start"
	echo "        starts daemon processes required for softap"
	echo ""
	echo "  ./softap stop"
	echo "        stops daemon processes required for softap"
	echo ""
	echo "  ./softap help"
	echo "        show this help message"
	echo ""
	echo ""
}


stop_softap(){
	# Initialization environment
	# pgrep wpa_supplicant | xargs kill -9 &>/dev/null
	systemctl disable --now hostapd
	systemctl disable --now dnsmasq


	# flush ip
	ip link set $AP_INTERFACE down
	# ip addr flush dev $AP_INTERFACE
	# ip link set $AP_INTERFACE up
	if [ "$?" -ne "0" ]; then
		echo "Cannot find $AP_INTERFACE"
		exit 1
	fi
}

start_softap(){
	echo "starting hostapd and dnsmasq for qrb5165"
	# start hostapd daemon
	hostapd -B /data/misc/wifi/hostapd.conf

	# set static ip
	ifconfig $AP_INTERFACE 192.168.8.1 up

	# resolved causes issues with concurrent station+softap modes, we use static dns instead
	systemctl disable --now systemd-resolved

	# start dnsmasq daemon
	dnsmasq -i $AP_INTERFACE --bind-interfaces \
		--dhcp-range=192.168.8.10,192.168.8.100,255.255.255.0,2m \
		--dhcp-option=option:router,192.168.8.1 \
		--dhcp-option=option:dns-server,1.1.1.1,8.8.8.8 \
		--dhcp-leasefile=/tmp/dnsmasq_uap0.leases \
		--no-resolv --dhcp-sequential-ip \
		--port=0

	# Forwarding configuration
	echo 1 > /proc/sys/net/ipv4/ip_forward
	iptables -t nat -A POSTROUTING -o eth0 -j MASQUERADE
}

CHIP=$(voxl-chip)
if ! [ $CHIP == "QRB5165" ]; then
	echo "ERROR, only use voxl-softap service with VOXL2 QRB5165 platoforms"
	exit 1
fi

# Detect interface before executing commands
detect_ap_interface

# parse cases
case "$1" in
	start)
		stop_softap
		echo "[INFO] Starting SoftAP on $AP_INTERFACE"
		start_softap
		;;
	stop)
		echo "[INFO] Stopping SoftAP on $AP_INTERFACE"
		stop_softap
		;;
	help)
		print_usage
		;;
	*)
		print_usage
		;;
esac

