#!/bin/bash

# Script to check if wifi is connected and start hotspot if not
# will also retreive unique RPi ID and store it to deviceID.txt
# script that starts at boot:
# @reboot /var/www/nebuleair_pro_4g/boot_hotspot.sh >> /var/www/nebuleair_pro_4g/logs/app.log 2>&1

OUTPUT_FILE="/var/www/nebuleair_pro_4g/wifi_list.csv"


echo "-------------------"
echo "-------------------"

echo "NebuleAir pro started at $(date)"

chmod -R 777 /var/www/nebuleair_pro_4g/

# Blink GPIO 23 and 24 five times (starts OFF, stays OFF at end)
#gpioset -c gpiochip0 -t 1s,1s,1s,1s,1s,1s,1s,1s,1s,1s,0 23=0 24=0

# Blink GPIO 23 and 24 five times (starts OFF, stays OFF at end)
python3 << 'EOF'
import RPi.GPIO as GPIO
import time

GPIO.setmode(GPIO.BCM)
GPIO.setwarnings(False)
GPIO.setup(23, GPIO.OUT)
GPIO.setup(24, GPIO.OUT)

for _ in range(5):
    GPIO.output(23, GPIO.HIGH)
    GPIO.output(24, GPIO.HIGH)
    time.sleep(1)
    GPIO.output(23, GPIO.LOW)
    GPIO.output(24, GPIO.LOW)
    time.sleep(1)

GPIO.cleanup()
EOF

echo "getting RPI serial number"
# Get the last 8 characters of the serial number and write to text file
serial_number=$(cat /proc/cpuinfo | grep Serial | awk '{print substr($3, length($3) - 7)}')

# update Sqlite database (only if not already set, i.e., still has default value 'XXXX')
echo "Updating SQLite database with device ID: $serial_number"
sqlite3 /var/www/nebuleair_pro_4g/sqlite/sensors.db "UPDATE config_table SET value='$serial_number' WHERE key='deviceID' AND value='XXXX';"

echo "id: $serial_number"

# Get deviceID from SQLite config_table (may be different from serial_number if manually configured)
DEVICE_ID=$(sqlite3 /var/www/nebuleair_pro_4g/sqlite/sensors.db "SELECT value FROM config_table WHERE key='deviceID'")
echo "Device ID from database: $DEVICE_ID"

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

# Get SSH tunnel port from SQLite config_table
SSH_TUNNEL_PORT=$(sqlite3 /var/www/nebuleair_pro_4g/sqlite/sensors.db "SELECT value FROM config_table WHERE key='sshTunnel_port'")

#need to wait for the network manager to be ready
sleep 20

# IMPORTANT: Always enable WiFi radio at boot (in case it was disabled by power save)
WIFI_RADIO_STATE=$(nmcli radio wifi)
echo "WiFi radio state: $WIFI_RADIO_STATE"

if [ "$WIFI_RADIO_STATE" == "disabled" ]; then
    echo "WiFi radio is disabled, enabling it..."
    nmcli radio wifi on
    # Wait longer for NetworkManager to scan and reconnect to known networks
    echo "Waiting 15 seconds for WiFi to reconnect to known networks..."
    sleep 15
else
    echo "WiFi radio is already enabled"
fi

# Get the connection state of wlan0
STATE=$(nmcli -g GENERAL.STATE device show wlan0)

# Check if the state is 'disconnected'
if [ "$STATE" == "30 (disconnected)" ]; then
    echo "wlan0 is disconnected."
    echo "need to perform a wifi scan"
    # Perform a wifi scan and save its output to a csv file    
    # nmcli device wifi list
    nmcli -f SSID,SIGNAL,SECURITY device wifi list | awk 'BEGIN { OFS=","; print "SSID,SIGNAL,SECURITY" } NR>1 { print $1,$2,$3 }' > "$OUTPUT_FILE"
    # Start the hotspot with SSID based on deviceName
    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'"

else
    echo "🛜Success: wlan0 is connected!🛜"
    CONN_SSID=$(nmcli -g GENERAL.CONNECTION device show wlan0)
    echo "Connection: $CONN_SSID"

    # Update SQLite to reflect hotspot mode
    sqlite3 /var/www/nebuleair_pro_4g/sqlite/sensors.db "UPDATE config_table SET value='connected' WHERE key='WIFI_status'"

    # Lancer le tunnel SSH
    #echo "Démarrage du tunnel SSH sur le port $SSH_TUNNEL_PORT..."
    # Start the SSH agent if it's not already running
    #eval "$(ssh-agent -s)"
    # Add your SSH private key
    #ssh-add /home/airlab/.ssh/id_rsa
    #connections details
    #REMOTE_USER="airlab_server1"    # Remplacez par votre nom d'utilisateur distant
    #REMOTE_SERVER="aircarto.fr"     # Remplacez par l'adresse de votre serveur
    #LOCAL_PORT=22                   # Port local à rediriger
    #MONITOR_PORT=0                  # Désactive la surveillance de connexion autossh
    
    #autossh -M "$MONITOR_PORT" -f -N -R "$SSH_TUNNEL_PORT:localhost:$LOCAL_PORT" "$REMOTE_USER@$REMOTE_SERVER" -p 50221
    # ssh -f -N -R 52221:localhost:22 -p 50221 airlab_server1@aircarto.fr
    #ssh -i /var/www/.ssh/id_rsa -f -N -R "$SSH_TUNNEL_PORT:localhost:$LOCAL_PORT" -p 50221 -o StrictHostKeyChecking=no "$REMOTE_USER@$REMOTE_SERVER" 

    #Check if the tunnel was created successfully
    #if [ $? -eq 0 ]; then
    #    echo "Tunnel started successfully!"
    #else
    #    echo "Error: Unable to start the tunnel!"
    #    exit 1
    #fi
fi
echo "-------------------"
