#!/bin/bash

# Complete Reliable Raspberry Pi Hotspot Setup
# This script sets up a WiFi hotspot with reliable automatic activation

# Text formatting
BOLD="\e[1m"
RED="\e[31m"
GREEN="\e[32m"
YELLOW="\e[33m"
BLUE="\e[34m"
RESET="\e[0m"

# Default values
SSID="RaspberryPi-Hotspot"
PASSWORD="raspberry"
INTERFACE="wlan0"

# Print usage information
function print_usage {
    echo -e "${BOLD}Usage:${RESET} $0 [OPTIONS]"
    echo -e ""
    echo -e "${BOLD}Options:${RESET}"
    echo -e "  -s, --ssid SSID       Hotspot SSID name (default: RaspberryPi-Hotspot)"
    echo -e "  -p, --password PASS   Hotspot password (min 8 chars, default: raspberry)"
    echo -e "  -i, --interface IFACE WiFi interface (default: wlan0)"
    echo -e "  -h, --help            Show this help message"
    echo -e ""
    echo -e "${BOLD}Example:${RESET}"
    echo -e "  $0 --ssid \"BirdNET-Hotspot\" --password \"schmoebirds\""
    echo -e ""
}

# Parse command line arguments
while [[ $# -gt 0 ]]; do
    case $1 in
        -s|--ssid)
            SSID="$2"
            shift 2
            ;;
        -p|--password)
            PASSWORD="$2"
            if [[ ${#PASSWORD} -lt 8 ]]; then
                echo -e "${RED}Error: Password must be at least 8 characters long${RESET}"
                exit 1
            fi
            shift 2
            ;;
        -i|--interface)
            INTERFACE="$2"
            shift 2
            ;;
        -h|--help)
            print_usage
            exit 0
            ;;
        *)
            echo -e "${RED}Error: Unknown option $1${RESET}"
            print_usage
            exit 1
            ;;
    esac
done

# Check if running as root
if [[ $EUID -ne 0 ]]; then
    echo -e "${RED}Error: This script must be run as root (sudo)${RESET}"
    exit 1
fi

echo -e "${BOLD}${BLUE}=== Complete Reliable Raspberry Pi Hotspot Setup ===${RESET}"
echo -e "This script sets up a WiFi hotspot with reliable automatic activation"
echo -e "when home WiFi is unavailable."
echo -e ""
echo -e "SSID: ${BOLD}$SSID${RESET}"
echo -e "Password: ${BOLD}$PASSWORD${RESET}"
echo -e "Interface: ${BOLD}$INTERFACE${RESET}"

# Create log directory if it doesn't exist
mkdir -p /var/log/hotspot

# Create a backup directory for existing configurations
echo -e "\n${BLUE}Creating backup of existing network configurations...${RESET}"
BACKUP_DIR="/root/network-config-backup-$(date +%Y%m%d%H%M%S)"
mkdir -p "$BACKUP_DIR"

# Backup existing network configurations
cp -r /etc/NetworkManager/system-connections/ "$BACKUP_DIR/" 2>/dev/null || true
cp /etc/hosts "$BACKUP_DIR/" 2>/dev/null || true
cp /etc/dhcpcd.conf "$BACKUP_DIR/" 2>/dev/null || true
cp /etc/wpa_supplicant/wpa_supplicant.conf "$BACKUP_DIR/" 2>/dev/null || true
echo -e "${GREEN}Backups saved to: $BACKUP_DIR${RESET}"

# -----------------------------------------------------
# PART 1: SYSTEM PREPARATION
# -----------------------------------------------------
echo -e "\n${BOLD}${BLUE}PART 1: SYSTEM PREPARATION${RESET}"

# Check if NetworkManager is installed
if ! command -v nmcli &> /dev/null; then
    echo -e "${RED}Error: NetworkManager (nmcli) is not installed.${RESET}"
    echo -e "Please install it with: sudo apt-get install network-manager"
    exit 1
fi

# Check NetworkManager version
NM_VERSION=$(nmcli --version)
echo "NetworkManager version: $NM_VERSION"
systemctl status NetworkManager | grep "Active:" | head -1

# Check if WiFi interface exists
if ! ip link show "$INTERFACE" &> /dev/null; then
    echo -e "${RED}Error: WiFi interface $INTERFACE not found${RESET}"
    echo -e "Available interfaces:"
    ip -br link show | grep -v "lo"
    exit 1
fi

# Check if the WiFi adapter supports AP mode
if ! iw list | grep -q "AP"; then
    echo -e "${RED}Error: Your WiFi adapter does not support Access Point mode${RESET}"
    echo -e "The script will continue, but hotspot functionality will not work."
    read -p "Continue anyway? (y/n): " -n 1 -r
    echo
    if [[ ! $REPLY =~ ^[Yy]$ ]]; then
        exit 1
    fi
fi

# Check for and disable potentially conflicting services
echo -e "\n${BLUE}Checking for conflicting services...${RESET}"

# Disable dhcpcd if active
if systemctl is-active --quiet dhcpcd; then
    echo -e "${YELLOW}Disabling dhcpcd service as it may conflict with NetworkManager...${RESET}"
    systemctl stop dhcpcd
    systemctl disable dhcpcd
    echo -e "${GREEN}dhcpcd service has been disabled to prevent conflicts${RESET}"
fi

# Make sure wpa_supplicant is managed by NetworkManager
if systemctl is-active --quiet wpa_supplicant.service; then
    echo -e "${YELLOW}Reconfiguring wpa_supplicant service to work with NetworkManager...${RESET}"
    systemctl stop wpa_supplicant.service
    systemctl disable wpa_supplicant.service
    echo -e "${GREEN}wpa_supplicant standalone service disabled${RESET}"
    
    # Restart NetworkManager to take control of WiFi
    echo -e "${YELLOW}Restarting NetworkManager to take control of WiFi...${RESET}"
    systemctl restart NetworkManager
    sleep 5
fi

# Ensure rfkill is not blocking WiFi
echo -e "\n${BLUE}Checking for radio kill switches...${RESET}"
if command -v rfkill &> /dev/null; then
    echo "Current rfkill status:"
    rfkill list
    
    echo "Unblocking all wireless devices..."
    rfkill unblock all
    echo -e "${GREEN}All wireless devices unblocked${RESET}"
else
    echo "rfkill command not found. Skipping this check."
fi

# -----------------------------------------------------
# PART 2: HOTSPOT SETUP
# -----------------------------------------------------
echo -e "\n${BOLD}${BLUE}PART 2: HOTSPOT SETUP${RESET}"

# Automatically detect home WiFi connection
echo -e "\n${BLUE}Detecting home WiFi connection...${RESET}"
# First check if there's a connection named "preconfigured"
if nmcli connection show | grep -q "preconfigured"; then
    HOME_WIFI="preconfigured"
    echo -e "${GREEN}Using 'preconfigured' as home network.${RESET}"
# Next, try to find the active connection
elif nmcli -t -f NAME,DEVICE connection show --active | grep -q "$INTERFACE"; then
    HOME_WIFI=$(nmcli -t -f NAME,DEVICE connection show --active | grep "$INTERFACE" | cut -d: -f1)
    echo -e "${GREEN}Using active connection '$HOME_WIFI' as home network.${RESET}"
# Finally, find the highest priority wifi connection
else
    # Find the highest priority connection that's not a hotspot
    HOME_WIFI=$(nmcli -t -f NAME,TYPE,AUTOCONNECT-PRIORITY connection show | grep ":wifi:" | sort -t: -k3 -nr | head -1 | cut -d: -f1)
    
    if [[ -z "$HOME_WIFI" ]]; then
        echo -e "${YELLOW}No home WiFi connection found. Hotspot will be the only WiFi connection.${RESET}"
    else
        echo -e "${GREEN}Using highest priority WiFi connection: $HOME_WIFI${RESET}"
    fi
fi

if [[ -n "$HOME_WIFI" ]]; then
    echo -e "Home WiFi connection: ${BOLD}$HOME_WIFI${RESET}"
fi

# Clean up any existing hotspot with the same SSID
echo -e "\n${BLUE}Checking for existing hotspot connections...${RESET}"
EXISTING_HOTSPOT=""

# Method 1: Check for same SSID
for conn in $(nmcli -t -f NAME connection show); do
    CONN_SSID=$(nmcli -g 802-11-wireless.ssid connection show "$conn" 2>/dev/null)
    if [[ "$CONN_SSID" == "$SSID" ]]; then
        EXISTING_HOTSPOT="$conn"
        echo -e "${YELLOW}Found existing hotspot with same SSID: $EXISTING_HOTSPOT${RESET}"
        break
    fi
done

# Method 2: Check for "hotspot" in name if no SSID match
if [[ -z "$EXISTING_HOTSPOT" ]]; then
    NAMED_HOTSPOT=$(nmcli -t -f NAME connection show | grep -i "hotspot" | head -1)
    if [[ -n "$NAMED_HOTSPOT" ]]; then
        EXISTING_HOTSPOT="$NAMED_HOTSPOT"
        echo -e "${YELLOW}Found existing hotspot by name: $EXISTING_HOTSPOT${RESET}"
    fi
fi

# Method 3: Check for AP mode if still no match
if [[ -z "$EXISTING_HOTSPOT" ]]; then
    for conn in $(nmcli -t -f NAME connection show); do
        if nmcli -g 802-11-wireless.mode connection show "$conn" 2>/dev/null | grep -q "ap"; then
            EXISTING_HOTSPOT="$conn"
            echo -e "${YELLOW}Found existing hotspot by mode: $EXISTING_HOTSPOT${RESET}"
            break
        fi
    done
fi

# Remove existing hotspot if found
if [[ -n "$EXISTING_HOTSPOT" ]]; then
    echo -e "${YELLOW}Removing existing hotspot connection: $EXISTING_HOTSPOT${RESET}"
    nmcli connection delete "$EXISTING_HOTSPOT"
    sleep 2
    echo -e "${GREEN}Existing hotspot removed${RESET}"
else
    echo -e "${GREEN}No existing hotspot connections found${RESET}"
fi

# Create the hotspot connection
echo -e "\n${BLUE}Creating hotspot connection...${RESET}"

# Make sure WiFi is on
nmcli radio wifi on

# Verify interface is available
if ! nmcli device | grep "$INTERFACE" | grep -q "wifi"; then
    echo -e "${RED}Error: WiFi interface $INTERFACE is not available to NetworkManager${RESET}"
    echo -e "Current device status:"
    nmcli device status
    
    echo -e "${YELLOW}Attempting to fix the interface...${RESET}"
    # Try to fix by resetting interface and restarting NetworkManager
    ip link set "$INTERFACE" down
    sleep 2
    ip link set "$INTERFACE" up
    sleep 2
    systemctl restart NetworkManager
    sleep 5
    
    # Check again
    if ! nmcli device | grep "$INTERFACE" | grep -q "wifi"; then
        echo -e "${RED}Failed to make interface available. Try rebooting your system.${RESET}"
        exit 1
    fi
    echo -e "${GREEN}Interface is now available.${RESET}"
fi

# Create the hotspot with retries
MAX_RETRIES=3
for (( i=1; i<=MAX_RETRIES; i++ )); do
    echo -e "Attempt $i/$MAX_RETRIES to create hotspot..."
    if nmcli device wifi hotspot ssid "$SSID" password "$PASSWORD" ifname "$INTERFACE"; then
        echo -e "${GREEN}Hotspot created successfully${RESET}"
        break
    else
        if [ $i -eq $MAX_RETRIES ]; then
            echo -e "${RED}Error: Failed to create hotspot after $MAX_RETRIES attempts${RESET}"
            echo -e "${YELLOW}Trying alternate method...${RESET}"
            
            # Try alternate method
            if nmcli connection add type wifi ifname "$INTERFACE" con-name "Hotspot" autoconnect no \
                ssid "$SSID" -- wifi-security.key-mgmt wpa-psk wifi-security.psk "$PASSWORD" \
                ipv4.method shared 802-11-wireless.mode ap; then
                echo -e "${GREEN}Hotspot created with alternate method${RESET}"
            else
                echo -e "${RED}All hotspot creation methods failed!${RESET}"
                exit 1
            fi
        fi
        echo -e "${YELLOW}Retrying in 5 seconds...${RESET}"
        sleep 5
    fi
done

# Get the actual hotspot connection name
HOTSPOT=$(nmcli -t -f NAME connection show | grep -v "$HOME_WIFI" | grep -i "hotspot" | head -1)
if [[ -z "$HOTSPOT" ]]; then
    # Try to find by SSID
    for conn in $(nmcli -t -f NAME connection show); do
        CONN_SSID=$(nmcli -g 802-11-wireless.ssid connection show "$conn" 2>/dev/null)
        if [[ "$CONN_SSID" == "$SSID" ]]; then
            HOTSPOT="$conn"
            break
        fi
    done
fi

# If still not found, look for AP mode
if [[ -z "$HOTSPOT" ]]; then
    for conn in $(nmcli -t -f NAME connection show); do
        if nmcli -g 802-11-wireless.mode connection show "$conn" 2>/dev/null | grep -q "ap"; then
            HOTSPOT="$conn"
            break
        fi
    done
fi

if [[ -z "$HOTSPOT" ]]; then
    echo -e "${RED}Error: Could not identify the created hotspot connection${RESET}"
    echo "Available connections:"
    nmcli connection show
    exit 1
fi

echo -e "${GREEN}Identified hotspot connection: ${BOLD}$HOTSPOT${RESET}"

# Configure network priorities
echo -e "\n${BLUE}Configuring network priorities...${RESET}"

# Configure home WiFi with maximum priority (if it exists)
if [[ -n "$HOME_WIFI" ]]; then
    echo "Setting home WiFi connection priority..."
    nmcli connection modify "$HOME_WIFI" connection.autoconnect yes
    nmcli connection modify "$HOME_WIFI" connection.autoconnect-priority 999
    nmcli connection modify "$HOME_WIFI" ipv4.route-metric 100
    echo -e "${GREEN}Home WiFi priority set${RESET}"
fi

# Configure hotspot with low priority
echo "Setting hotspot connection priority..."
nmcli connection modify "$HOTSPOT" connection.autoconnect no
nmcli connection modify "$HOTSPOT" connection.autoconnect-priority 0
nmcli connection modify "$HOTSPOT" ipv4.route-metric 900
echo -e "${GREEN}Hotspot priority set${RESET}"

# -----------------------------------------------------
# PART 3: NETWORK SWITCHING SCRIPTS
# -----------------------------------------------------
echo -e "\n${BOLD}${BLUE}PART 3: NETWORK SWITCHING SCRIPTS${RESET}"

# Create the check network script for regular network checking
echo -e "\n${BLUE}Creating network check script...${RESET}"
CHECK_SCRIPT="/usr/local/bin/check-network.sh"

cat > "$CHECK_SCRIPT" << EOF
#!/bin/bash

# Log file for debugging
LOG_FILE="/var/log/hotspot/check-network.log"
mkdir -p /var/log/hotspot
touch "\$LOG_FILE"
chmod 644 "\$LOG_FILE" 
exec >> "\$LOG_FILE" 2>&1

echo "Starting check-network.sh at \$(date)"

# Define your home WiFi connection
HOME_WIFI="$HOME_WIFI"
HOTSPOT="$HOTSPOT"
INTERFACE="$INTERFACE"

echo "HOME_WIFI=\$HOME_WIFI"
echo "HOTSPOT=\$HOTSPOT"

# Function to check if home network is available
check_home_network() {
  # Ensure WiFi is enabled
  nmcli radio wifi on
  echo "WiFi radio enabled"
  
  # Scan for networks with proper delay
  echo "Scanning for WiFi networks..."
  nmcli device wifi rescan || true
  
  # Wait for scan to complete with multiple checks
  for i in {1..3}; do
    sleep 3
    echo "Scan check \$i..."
    
    # First check if the connection exists in NetworkManager
    if nmcli -t connection | grep -q "^\$HOME_WIFI:"; then
      echo "Home WiFi connection found in NetworkManager"
      
      # Get the SSID of the home WiFi
      HOME_SSID=\$(nmcli -g 802-11-wireless.ssid connection show "\$HOME_WIFI" 2>/dev/null)
      echo "Home SSID: \$HOME_SSID"
      
      # Check if the network is actually in range
      if [[ -n "\$HOME_SSID" ]] && nmcli dev wifi list | grep -q -i "\$HOME_SSID"; then
        echo "Home network SSID found in scan results"
        return 0  # Home network found
      else
        echo "Home network SSID not found in scan results"
      fi
    else
      echo "Home WiFi connection not found in NetworkManager"
    fi
  done
  
  echo "Home network not available after multiple checks"
  return 1  # Home network not found
}

# Check current connection state
echo "Checking current connection state..."
CURRENT=\$(nmcli -t -f NAME connection show --active)
echo "Current active connections: \$CURRENT"

# If we're already on the home network, do nothing
if [[ "\$CURRENT" == *"\$HOME_WIFI"* ]]; then
  echo "Already connected to home network."
  exit 0
fi

# If we're in hotspot mode, check if home network is available
if [[ "\$CURRENT" == *"\$HOTSPOT"* ]]; then
  echo "Currently in hotspot mode, checking for home network..."
  if check_home_network; then
    echo "Home network detected. Switching from hotspot mode..."
    nmcli connection down "\$HOTSPOT"
    nmcli connection up "\$HOME_WIFI"
    
    # Verify home WiFi connection succeeded
    sleep 3
    if ! nmcli -t -f NAME connection show --active | grep -q "\$HOME_WIFI"; then
      echo "Failed to connect to home network. Restoring hotspot mode..."
      nmcli connection up "\$HOTSPOT"
    else
      echo "Connected to home network."
    fi
  else
    echo "Home network not available. Staying in hotspot mode."
  fi
  exit 0
fi

# If we're not connected to either, try home network first
echo "Not connected to home network or hotspot. Checking for home network..."
if check_home_network; then
  echo "Home network available. Connecting..."
  nmcli connection up "\$HOME_WIFI"
  
  # Verify connection
  sleep 3
  if ! nmcli -t -f NAME connection show --active | grep -q "\$HOME_WIFI"; then
    echo "Failed to connect to home network. Starting hotspot..."
    nmcli connection up "\$HOTSPOT"
  else
    echo "Connected to home network."
  fi
else
  echo "Home network not available. Starting hotspot..."
  nmcli connection up "\$HOTSPOT"
  
  # Verify hotspot is active
  sleep 3
  if ! nmcli -t -f NAME connection show --active | grep -q "\$HOTSPOT"; then
    echo "Failed to activate hotspot. Please check your network configuration."
    exit 1
  else
    echo "Hotspot activated successfully."
  fi
fi

echo "check-network.sh completed at \$(date)"
EOF

chmod +x "$CHECK_SCRIPT"
echo -e "${GREEN}Created network check script: $CHECK_SCRIPT${RESET}"

# Create the force hotspot script for reliable activation
echo -e "\n${BLUE}Creating force hotspot script...${RESET}"
FORCE_SCRIPT="/usr/local/bin/force-hotspot.sh"

cat > "$FORCE_SCRIPT" << EOF
#!/bin/bash

# Force hotspot activation script
# This script aggressively activates the hotspot

# Log everything
LOG_FILE="/var/log/hotspot/force-hotspot.log"
mkdir -p /var/log/hotspot
touch "\$LOG_FILE"
chmod 644 "\$LOG_FILE" 
exec >> "\$LOG_FILE" 2>&1

echo "===== Starting force-hotspot.sh at \$(date) ====="

# Hotspot connection name
HOTSPOT="$HOTSPOT"
INTERFACE="$INTERFACE"

# Show current status for debugging
echo "Current NetworkManager device status:"
nmcli device status

echo "Current active connections:"
nmcli connection show --active

# Ensure WiFi is enabled
echo "Ensuring WiFi radio is on..."
nmcli radio wifi on
sleep 2

# Test for actual internet connectivity
echo "Testing internet connectivity..."
if ping -c 1 -W 5 8.8.8.8 &>/dev/null; then
    echo "Internet is working - no need to activate hotspot"
else
    echo "No internet connectivity detected - will activate hotspot"
    
    # Force disconnect any active connections on WiFi interface
    echo "Forcibly disconnecting any WiFi connections..."
    nmcli device disconnect "\$INTERFACE" || true
    sleep 3
    
    # Reset the interface completely
    echo "Resetting WiFi interface..."
    ip link set "\$INTERFACE" down || true
    sleep 2
    ip link set "\$INTERFACE" up || true
    sleep 5
    
    # Ensure rfkill isn't blocking
    echo "Ensuring no rfkill blocks..."
    rfkill unblock wifi || true
    sleep 1
    
    # Try up to 3 times to activate the hotspot
    for i in {1..3}; do
        echo "Attempt \$i to activate hotspot..."
        nmcli connection up "\$HOTSPOT" || true
        
        sleep 5
        
        if nmcli connection show --active | grep -q "\$HOTSPOT"; then
            echo "Success! Hotspot is now active."
            break
        fi
        
        echo "Attempt \$i failed. Retrying..."
        sleep 2
    done
    
    # Final check
    if ! nmcli connection show --active | grep -q "\$HOTSPOT"; then
        echo "All standard attempts failed. Trying direct device method..."
        nmcli device wifi hotspot con-name "\$HOTSPOT" ifname "\$INTERFACE" || true
        sleep 5
    fi
    
    # Report final status
    if nmcli connection show --active | grep -q "\$HOTSPOT"; then
        echo "Hotspot activation SUCCESSFUL"
    else
        echo "Hotspot activation FAILED"
    fi
fi

echo "Force-hotspot script completed at \$(date)"
EOF

chmod +x "$FORCE_SCRIPT"
echo -e "${GREEN}Created force hotspot script: $FORCE_SCRIPT${RESET}"

# Create manual toggle script
echo -e "\n${BLUE}Creating manual toggle script...${RESET}"
TOGGLE_SCRIPT="/usr/local/bin/wifi-toggle.sh"

cat > "$TOGGLE_SCRIPT" << EOF
#!/bin/bash

# Get the current active connection
CURRENT=\$(nmcli -t -f NAME connection show --active)

# Define your connection names
HOME_WIFI="$HOME_WIFI"
HOTSPOT="$HOTSPOT"

if [[ "\$CURRENT" == *"\$HOME_WIFI"* ]]; then
  echo "Switching from home WiFi to hotspot mode..."
  nmcli connection down "\$HOME_WIFI"
  nmcli connection up "\$HOTSPOT"
  # Verify hotspot is active
  sleep 3
  if ! nmcli -t -f NAME connection show --active | grep -q "\$HOTSPOT"; then
    echo "Error: Failed to activate hotspot. Attempting to reconnect to home WiFi..."
    nmcli connection up "\$HOME_WIFI"
  else
    echo "Hotspot mode activated."
    echo "SSID: $SSID"
    echo "Password: $PASSWORD"
  fi
else
  echo "Switching from hotspot to home WiFi..."
  nmcli connection down "\$HOTSPOT"
  nmcli connection up "\$HOME_WIFI"
  # Verify home WiFi connection
  sleep 3
  if ! nmcli -t -f NAME connection show --active | grep -q "\$HOME_WIFI"; then
    echo "Error: Failed to connect to home WiFi. Restoring hotspot..."
    nmcli connection up "\$HOTSPOT"
  else
    echo "Connected to home WiFi."
  fi
fi
EOF

chmod +x "$TOGGLE_SCRIPT"
echo -e "${GREEN}Created toggle script: $TOGGLE_SCRIPT${RESET}"

# Create simple activation script
echo -e "\n${BLUE}Creating direct activation script...${RESET}"
ACTIVATE_SCRIPT="/usr/local/bin/activate-hotspot.sh"

cat > "$ACTIVATE_SCRIPT" << EOF
#!/bin/bash

# Direct hotspot activation script
echo "Activating hotspot..."
$FORCE_SCRIPT
echo "Done!"
EOF

chmod +x "$ACTIVATE_SCRIPT"
echo -e "${GREEN}Created direct activation script: $ACTIVATE_SCRIPT${RESET}"

# Create symlink for toggle-wifi command
ln -sf "$TOGGLE_SCRIPT" /usr/local/bin/toggle-wifi
chmod +x /usr/local/bin/toggle-wifi
echo -e "${GREEN}Created toggle-wifi command${RESET}"

# -----------------------------------------------------
# PART 4: AUTOMATIC ACTIVATION SETUP
# -----------------------------------------------------
echo -e "\n${BOLD}${BLUE}PART 4: AUTOMATIC ACTIVATION SETUP${RESET}"

# Create systemd service for regular network checking
echo -e "\n${BLUE}Creating systemd services...${RESET}"
SERVICE_FILE="/etc/systemd/system/auto-network.service"

cat > "$SERVICE_FILE" << EOF
[Unit]
Description=Auto Network Selector
After=NetworkManager.service network-online.target
Wants=NetworkManager.service network-online.target
StartLimitIntervalSec=500
StartLimitBurst=5

[Service]
Type=oneshot
ExecStartPre=/bin/sleep 20
ExecStart=$CHECK_SCRIPT
Restart=on-failure
RestartSec=10s

[Install]
WantedBy=multi-user.target
EOF

# Create timer for regular network checking
TIMER_FILE="/etc/systemd/system/auto-network.timer"

cat > "$TIMER_FILE" << EOF
[Unit]
Description=Periodically check for home network when in hotspot mode

[Timer]
OnBootSec=30s
OnUnitActiveSec=2min

[Install]
WantedBy=timers.target
EOF

# Create force hotspot service
FORCE_SERVICE_FILE="/etc/systemd/system/force-hotspot.service"

cat > "$FORCE_SERVICE_FILE" << EOF
[Unit]
Description=Force Hotspot Activation
After=NetworkManager.service network-online.target
Wants=NetworkManager.service network-online.target

[Service]
Type=oneshot
ExecStartPre=/bin/sleep 45
ExecStart=$FORCE_SCRIPT
TimeoutStartSec=180

[Install]
WantedBy=multi-user.target
EOF

# Create force hotspot timer
FORCE_TIMER_FILE="/etc/systemd/system/force-hotspot.timer"

cat > "$FORCE_TIMER_FILE" << EOF
[Unit]
Description=Run force-hotspot periodically

[Timer]
OnBootSec=60s
OnUnitActiveSec=3min

[Install]
WantedBy=timers.target
EOF

# Enable all services
systemctl daemon-reload
systemctl enable auto-network.service
systemctl enable auto-network.timer
systemctl start auto-network.timer
systemctl enable force-hotspot.service
systemctl enable force-hotspot.timer
systemctl start force-hotspot.timer

echo -e "${GREEN}Created and enabled systemd services and timers${RESET}"

# Create NetworkManager dispatcher scripts
echo -e "\n${BLUE}Creating NetworkManager dispatcher scripts...${RESET}"

# Standard dispatcher for network changes
DISPATCHER_SCRIPT="/etc/NetworkManager/dispatcher.d/90-auto-hotspot"

cat > "$DISPATCHER_SCRIPT" << EOF
#!/bin/bash

# Log file for debugging
LOG_FILE="/var/log/hotspot/nm-auto-hotspot.log"
mkdir -p /var/log/hotspot
touch "\$LOG_FILE"
chmod 644 "\$LOG_FILE"
exec >> "\$LOG_FILE" 2>&1

echo "==== Dispatcher called at \$(date) ===="
echo "Interface: \$1"
echo "Action: \$2"

# Only for WiFi interface and useful events
if [ "\$1" == "$INTERFACE" ]; then
    if [ "\$2" == "down" ] || [ "\$2" == "connectivity-change" ]; then
        echo "Relevant event detected. Waiting 5 seconds before checking..."
        sleep 5
        
        # Check if we're connected to anything
        if ! nmcli device status | grep "\$1" | grep -q "connected"; then
            echo "No WiFi connection active. Running force-hotspot.sh"
            $FORCE_SCRIPT
        else
            echo "Already connected to a network. No action needed."
        fi
    fi
fi
EOF

chmod 755 "$FORCE_DISPATCHER_SCRIPT"
chown root:root "$FORCE_DISPATCHER_SCRIPT"
echo -e "${GREEN}Created NetworkManager dispatcher scripts${RESET}"

# Create cron job as an extra failsafe
echo -e "\n${BLUE}Setting up cron job failsafe...${RESET}"

CRON_SCRIPT="/usr/local/bin/cron-hotspot.sh"
cat > "$CRON_SCRIPT" << EOF
#!/bin/bash

# Cron job for hotspot activation
# Runs from cron, redirects all output to log

LOG_FILE="/var/log/hotspot/cron-hotspot.log"
mkdir -p /var/log/hotspot
exec >> "\$LOG_FILE" 2>&1

echo "--- Cron hotspot check at \$(date) ---"

# Only run if we're not connected to anything
if ! nmcli device status | grep $INTERFACE | grep -q "connected"; then
    echo "No connection detected. Running force-hotspot.sh"
    /usr/local/bin/force-hotspot.sh
else
    echo "WiFi is connected. No action needed."
fi
EOF

chmod +x "$CRON_SCRIPT"

# Add cron job
CRON_ENTRY="*/5 * * * * /usr/local/bin/cron-hotspot.sh"
(crontab -l 2>/dev/null | grep -v "cron-hotspot.sh"; echo "$CRON_ENTRY") | crontab -

echo -e "${GREEN}Created cron job to check every 5 minutes${RESET}"

# Create alias for toggle-wifi command
echo -e "\n${BLUE}Creating aliases for easy access...${RESET}"
ALIAS_FILE="/etc/profile.d/wifi-toggle-alias.sh"

echo "alias toggle-wifi='sudo $TOGGLE_SCRIPT'" > "$ALIAS_FILE"
chmod 644 "$ALIAS_FILE"
echo -e "${GREEN}Added system-wide 'toggle-wifi' alias to $ALIAS_FILE${RESET}"

# Add to current user's .bashrc for immediate use
if [ -f "$HOME/.bashrc" ]; then
    if ! grep -q "alias toggle-wifi=" "$HOME/.bashrc"; then
        echo "alias toggle-wifi='sudo $TOGGLE_SCRIPT'" >> "$HOME/.bashrc"
        echo -e "${GREEN}Added 'toggle-wifi' alias to current user's .bashrc${RESET}"
    fi
fi

# -----------------------------------------------------
# PART 5: VERIFICATION AND SUMMARY
# -----------------------------------------------------
echo -e "\n${BOLD}${BLUE}PART 5: VERIFICATION AND SUMMARY${RESET}"

# Verify services are enabled
echo -e "\n${BLUE}Verifying service setup...${RESET}"
echo "Auto-network service status:"
systemctl is-enabled auto-network.service
echo "Auto-network timer status:"
systemctl is-enabled auto-network.timer
echo "Force-hotspot service status:"
systemctl is-enabled force-hotspot.service
echo "Force-hotspot timer status:"
systemctl is-enabled force-hotspot.timer

# Show scripts created
echo -e "\n${BLUE}Scripts created:${RESET}"
ls -la /usr/local/bin/wifi-toggle.sh
ls -la /usr/local/bin/check-network.sh
ls -la /usr/local/bin/force-hotspot.sh
ls -la /usr/local/bin/activate-hotspot.sh
ls -la /usr/local/bin/cron-hotspot.sh

# Show connection details
echo -e "\n${BLUE}Connection details:${RESET}"
echo "Home WiFi connection:"
if [[ -n "$HOME_WIFI" ]]; then
    echo "$HOME_WIFI"
    nmcli -f connection.autoconnect,connection.autoconnect-priority,ipv4.route-metric connection show "$HOME_WIFI"
else
    echo "No home WiFi connection configured."
fi

echo "Hotspot connection:"
echo "$HOTSPOT"
nmcli -f connection.autoconnect,connection.autoconnect-priority,ipv4.route-metric connection show "$HOTSPOT"

# Final summary
echo -e "\n${BOLD}${GREEN}=== Hotspot Setup Complete! ===${RESET}"
echo -e "\n${BOLD}Hotspot Details:${RESET}"
echo -e "SSID: ${BOLD}$SSID${RESET}"
echo -e "Password: ${BOLD}$PASSWORD${RESET}"
echo -e "Interface: ${BOLD}$INTERFACE${RESET}"

echo -e "\n${BOLD}Automatic Activation Methods:${RESET}"
echo -e "1. At boot time (standard check after 20s, aggressive check after 45s)"
echo -e "2. Every 2 minutes via auto-network timer"
echo -e "3. Every 3 minutes via force-hotspot timer"
echo -e "4. Every 5 minutes via cron job"
echo -e "5. On network events via NetworkManager dispatcher scripts"

echo -e "\n${BOLD}Manual Control:${RESET}"
echo -e "1. To toggle between WiFi and hotspot: ${BOLD}toggle-wifi${RESET}"
echo -e "2. To force hotspot activation: ${BOLD}sudo /usr/local/bin/activate-hotspot.sh${RESET}"

echo -e "\n${BOLD}Log Files:${RESET}"
echo -e "All logs are in the ${BOLD}/var/log/hotspot/${RESET} directory:"
echo -e "- Regular check script: ${BOLD}check-network.log${RESET}"
echo -e "- Force activation script: ${BOLD}force-hotspot.log${RESET}"
echo -e "- NetworkManager regular script: ${BOLD}nm-auto-hotspot.log${RESET}"
echo -e "- NetworkManager force script: ${BOLD}nm-force-hotspot.log${RESET}"
echo -e "- Cron job: ${BOLD}cron-hotspot.log${RESET}"

echo -e "\n${YELLOW}Your hotspot is now set up with multiple redundant activation methods.${RESET}"
echo -e "${YELLOW}The system will prefer your home WiFi when available and${RESET}"
echo -e "${YELLOW}automatically activate the hotspot when home WiFi is unavailable.${RESET}"

echo -e "\n${BOLD}To test the setup:${RESET}"
echo -e "1. Disable your home WiFi access point"
echo -e "2. Reboot your Raspberry Pi"
echo -e "3. The hotspot should activate automatically within 1-2 minutes"
echo -e ""
