# Network monitor and auto-service starter
# Monitors for home network connection and starts services

HOME_NETWORK_SSID="The Bunker V3"  # Replace with your home network name
HOME_NETWORK_IP_RANGE="10.0.0"  # Your home network IP prefix
LOG_FILE="$HOME/logs/network-monitor.log"
SERVICES_STARTED=false

# Ensure logs directory exists
mkdir -p ~/logs

log() {
    echo "$(date '+%Y-%m-%d %H:%M:%S') - $1" | tee -a "$LOG_FILE"
}

check_home_network() {
    # Check if connected to home network by IP range
    current_ip=$(ifconfig 2>/dev/null | grep -A1 wlan0 | grep inet | awk '{print $2}' | cut -d: -f2)
    
    if [[ "$current_ip" == $HOME_NETWORK_IP_RANGE* ]]; then
        return 0  # On home network
    else
        return 1  # Not on home network
    fi
}

start_services() {
    if [ "$SERVICES_STARTED" = false ]; then
        log "🏠 Home network detected - starting services..."
        ~/bin/start-all-services.sh >> "$LOG_FILE" 2>&1
        SERVICES_STARTED=true
        log "✅ Services startup completed"
    fi
}

stop_services() {
    if [ "$SERVICES_STARTED" = true ]; then
        log "🌍 Left home network - stopping services..."
        pkill -f "termux-sms-api-server.py" 2>/dev/null
        pkill -f "python app.py" 2>/dev/null
        SERVICES_STARTED=false
        log "⏹️ Services stopped"
    fi
}

log "📡 Network monitor started"

# Main monitoring loop
while true; do
    if check_home_network; then
        start_services
    else
        stop_services
    fi
    
    # Check every 30 seconds
    sleep 30
done
