#!/bin/bash
echo "-------"
echo "Start connexion 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"

# Find and disable any active hotspot connection
echo "Disable Hotspot..."
# Get all wireless connections that are currently active (excludes the target WiFi)
ACTIVE_HOTSPOT=$(nmcli -t -f NAME,TYPE,DEVICE connection show --active | grep ':802-11-wireless:wlan0' | cut -d: -f1)

if [ -n "$ACTIVE_HOTSPOT" ]; then
    echo "Disabling hotspot connection: $ACTIVE_HOTSPOT"
    sudo nmcli connection down "$ACTIVE_HOTSPOT"
else
    echo "No active hotspot found"
fi

sleep 5

echo "Start connection with:"
echo "SSID: $1"
echo "Password: [HIDDEN]"
sudo nmcli device wifi connect "$1" password "$2"

# Check if connection is successful
if [ $? -eq 0 ]; then
    echo "Connection to $1 is successful"

    # Update SQLite to reflect connected status
    sqlite3 /var/www/nebuleair_pro_4g/sqlite/sensors.db "UPDATE config_table SET value='connected' WHERE key='WIFI_status'"
    echo "Updated database: WIFI_status = connected"
else
    echo "Connection to $1 failed"
    echo "Restarting hotspot..."

    # Recreate hotspot with current deviceName as SSID
    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 restarted with SSID: $DEVICE_NAME"
fi

echo "End connexion shell script"
echo "-------"


