#!/bin/bash
################################################################################
# Copyright 2021 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.
################################################################################

# Detect WiFi AP interface with retry logic
detect_ap_interface() {
	local max_wait=30
	local count=0
	
	echo "Detecting WiFi AP interface..."
	
	while [ $count -lt $max_wait ]; do
		if [ -d /sys/class/net/uap0 ]; then
			AP_INTERFACE="uap0"
			echo "Detected AP interface: $AP_INTERFACE"
			return 0
		elif [ -d /sys/class/net/wlan0 ]; then
			AP_INTERFACE="wlan0"
			echo "Detected AP interface: $AP_INTERFACE"
			return 0
		fi
		
		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
    pgrep hostapd | xargs kill -9 &>/dev/null
    pgrep dnsmasq | xargs kill -9 &>/dev/null

	# M0052 starts interfaces slower than M0054 on bootup, wait a bit before starting
    PLATFORM=$(voxl-platform)
	if [ $PLATFORM == "M0052" ]; then
        ifconfig $AP_INTERFACE 2>/dev/null >/dev/null
        if [ "$?" -ne "0" ]; then
            sleep 2
        fi
	fi

    # flush ip
	ip link set $AP_INTERFACE down
	ip addr flush dev $AP_INTERFACE
	ip link set $AP_INTERFACE up
	if [ "$?" -ne "0" ]; then
    	if [ $PLATFORM == "M0052" ]; then
    	    echo "Cannot find $AP_INTERFACE, make sure wifi dongle is connected and supported"
	    elif [ $PLATFORM == "M0054" ]; then
		    echo "Cannot find $AP_INTERFACE"
	    fi
	    exit 1
	fi
}

start_softap(){
    # start hostapd daemon
    hostapd -B /data/misc/wifi/hostapd.conf

    # set static ip
    ifconfig $AP_INTERFACE 192.168.8.1 up

    systemctl stop systemd-resolved

    # start dnsmasq daemon
    dnsmasq -i $AP_INTERFACE --dhcp-range=192.168.8.10,192.168.8.100,2m --dhcp-leasefile=/tmp/dnsmasq_d.leases --no-resolv --dhcp-sequential-ip
                      
    # Forwarding configuration 
    echo 1 > /proc/sys/net/ipv4/ip_forward
    iptables -t nat -A POSTROUTING -o eth0 -j MASQUERADE
}

# 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
