#!/bin/bash
echo "-------"
echo "Start forget WiFi shell script at $(date)"

# Get deviceName from database for hotspot SSID
DEVICE_NAME=$(sqlite3 /var/www/nebuleair_pro_4g/sqlite/sensors.db "SELECT value FROM config_table WHERE key='deviceName'")
echo "Device Name: $DEVICE_NAME"

# Get current active WiFi connection name
ACTIVE_WIFI=$(nmcli -t -f NAME,TYPE,DEVICE connection show --active | grep ':802-11-wireless:wlan0' | cut -d: -f1)

if [ -z "$ACTIVE_WIFI" ]; then
    echo "No active WiFi connection found on wlan0"
    echo "End forget WiFi shell script"
    echo "-------"
    exit 1
fi

echo "Forgetting WiFi connection: $ACTIVE_WIFI"

# Disconnect wlan0 first to prevent NetworkManager from auto-reconnecting
sudo nmcli device disconnect wlan0
echo "wlan0 disconnected"

# Delete (forget) the saved connection
sudo nmcli connection delete "$ACTIVE_WIFI"

if [ $? -eq 0 ]; then
    echo "Connection '$ACTIVE_WIFI' deleted successfully"
else
    echo "Failed to delete connection '$ACTIVE_WIFI'"
fi

sleep 5

# Scan WiFi networks BEFORE starting hotspot (scan impossible once hotspot is active)
OUTPUT_FILE="/var/www/nebuleair_pro_4g/wifi_list.csv"
echo "Scanning WiFi networks (waiting for wlan0 to be ready)..."
nmcli device wifi rescan ifname wlan0 2>/dev/null
sleep 3
nmcli -f SSID,SIGNAL,SECURITY device wifi list ifname wlan0 | awk 'BEGIN { OFS=","; print "SSID,SIGNAL,SECURITY" } NR>1 { print $1,$2,$3 }' > "$OUTPUT_FILE"
echo "WiFi scan saved to $OUTPUT_FILE"
cat "$OUTPUT_FILE"

# Start hotspot
echo "Starting hotspot with SSID: $DEVICE_NAME"
sudo nmcli device wifi hotspot ifname wlan0 ssid "$DEVICE_NAME" password nebuleaircfg

# Update SQLite to reflect hotspot mode
sqlite3 /var/www/nebuleair_pro_4g/sqlite/sensors.db "UPDATE config_table SET value='hotspot' WHERE key='WIFI_status'"
echo "Updated database: WIFI_status = hotspot"
echo "Hotspot started with SSID: $DEVICE_NAME"

echo "End forget WiFi shell script"
echo "-------"
