@echo off
setlocal EnableExtensions EnableDelayedExpansion
title MQTT Mosquitto Full Fix - AUTO IP DETECT
color 0A

echo ============================================================
echo   MQTT MOSQUITTO FULL FIX SCRIPT
echo   Fix for: Error: connect ECONNREFUSED AUTO_IP:1883
echo ============================================================
echo.

:: -------------------------------
:: Admin check
:: -------------------------------
net session >nul 2>&1
if not "%errorlevel%"=="0" (
    echo [ERROR] Please run this BAT file as Administrator.
    echo Right click on file ^> Run as Administrator
    pause
    exit /b 1
)

:: -------------------------------
:: Config
:: -------------------------------
set "TARGET_PORT=1883"
set "TARGET_IP="
set "MOSQ_DIR=C:\Program Files\Mosquitto"
set "MOSQ_EXE=%MOSQ_DIR%\mosquitto.exe"
set "MOSQ_SUB=%MOSQ_DIR%\mosquitto_sub.exe"
set "MOSQ_PUB=%MOSQ_DIR%\mosquitto_pub.exe"
set "MOSQ_CONF=%MOSQ_DIR%\mosquitto.conf"
set "TEST_TOPIC=test/fix"
set "TEST_MSG=hello_from_bat_test"

:: -------------------------------
:: Auto detect local IPv4
:: -------------------------------
echo [STEP] Detecting current local IPv4 address...

for /f "tokens=2 delims=:" %%A in ('ipconfig ^| findstr /R /C:"IPv4 Address" /C:"IPv4-adres"') do (
    set "RAW_IP=%%A"
    set "RAW_IP=!RAW_IP: =!"
    echo !RAW_IP! | findstr /V /C:"127.0.0.1" >nul && (
        set "TARGET_IP=!RAW_IP!"
        goto :ip_found
    )
)

:ip_found
if not defined TARGET_IP (
    echo [ERROR] Could not detect a valid local IPv4 address.
    echo Please check network connection and try again.
    pause
    exit /b 1
)

echo [OK] Auto detected local IPv4 : %TARGET_IP%
echo [INFO] Target Broker Port     : %TARGET_PORT%
echo.

:: -------------------------------
:: Check installation
:: -------------------------------
if not exist "%MOSQ_EXE%" (
    echo [ERROR] Mosquitto is not installed at:
    echo         %MOSQ_EXE%
    echo.
    echo Install Mosquitto first, then run this BAT again.
    pause
    exit /b 1
)

echo [OK] Mosquitto found.
echo.

:: -------------------------------
:: Show local IP addresses
:: -------------------------------
echo [INFO] Your current IPv4 addresses:
for /f "tokens=2 delims=:" %%A in ('ipconfig ^| findstr /R /C:"IPv4 Address" /C:"IPv4-adres"') do (
    set "SHOW_IP=%%A"
    set "SHOW_IP=!SHOW_IP: =!"
    echo     !SHOW_IP!
)
echo.

:: -------------------------------
:: Stop Mosquitto service if present
:: -------------------------------
echo [STEP] Stopping Mosquitto service if running...
sc query mosquitto >nul 2>&1
if "%errorlevel%"=="0" (
    net stop mosquitto >nul 2>&1
    timeout /t 2 >nul
    echo [OK] Mosquitto service stop command sent.
) else (
    echo [INFO] Mosquitto Windows service not found. Skipping service stop.
)
echo.

:: -------------------------------
:: Kill any process using port 1883
:: -------------------------------
echo [STEP] Checking processes using port %TARGET_PORT%...
set "FOUNDPORT=0"
for /f "tokens=5" %%P in ('netstat -ano ^| findstr /R /C:":%TARGET_PORT% .*LISTENING"') do (
    set "FOUNDPORT=1"
    echo [INFO] Killing PID %%P using port %TARGET_PORT% ...
    taskkill /PID %%P /F >nul 2>&1
)

for /f "tokens=5" %%P in ('netstat -ano ^| findstr /C:":%TARGET_PORT%"') do (
    echo [INFO] Killing PID %%P using port %TARGET_PORT% ...
    taskkill /PID %%P /F >nul 2>&1
)

if "!FOUNDPORT!"=="0" (
    echo [OK] Port %TARGET_PORT% was already free.
) else (
    echo [OK] Existing process cleanup attempted.
)
timeout /t 2 >nul
echo.

:: -------------------------------
:: Create fresh mosquitto.conf
:: -------------------------------
echo [STEP] Creating fresh Mosquitto config...
if exist "%MOSQ_CONF%" (
    copy /Y "%MOSQ_CONF%" "%MOSQ_CONF%.backup" >nul 2>&1
    echo [INFO] Backup created: %MOSQ_CONF%.backup
)

(
echo # Auto-generated by mqtt_fix_full_auto_ip.bat
echo # Remote access enabled for LAN testing
echo listener 1883
echo allow_anonymous true
echo persistence true
echo persistence_location C:\Program Files\Mosquitto\
echo log_type all
) > "%MOSQ_CONF%"

if exist "%MOSQ_CONF%" (
    echo [OK] Config written: %MOSQ_CONF%
) else (
    echo [ERROR] Failed to create config file.
    pause
    exit /b 1
)
echo.

:: -------------------------------
:: Firewall rules
:: -------------------------------
echo [STEP] Adding Windows Firewall rules...
netsh advfirewall firewall delete rule name="MQTT 1883 TCP IN" >nul 2>&1
netsh advfirewall firewall delete rule name="MQTT 1883 TCP OUT" >nul 2>&1
netsh advfirewall firewall add rule name="MQTT 1883 TCP IN" dir=in action=allow protocol=TCP localport=1883 >nul 2>&1
netsh advfirewall firewall add rule name="MQTT 1883 TCP OUT" dir=out action=allow protocol=TCP localport=1883 >nul 2>&1
echo [OK] Firewall rules added.
echo.

:: -------------------------------
:: Start Mosquitto
:: -------------------------------
echo [STEP] Starting Mosquitto broker...
cd /d "%MOSQ_DIR%"
start "Mosquitto Broker" /min cmd /c ""%MOSQ_EXE%" -c "%MOSQ_CONF%" -v"
timeout /t 4 >nul

:: -------------------------------
:: Check listening state
:: -------------------------------
echo [STEP] Checking whether broker is listening on port %TARGET_PORT%...
set "LISTEN_OK=0"
for /f "tokens=1,2,3,4,5" %%A in ('netstat -ano ^| findstr /R /C:":%TARGET_PORT% .*LISTENING"') do (
    set "LISTEN_OK=1"
    echo [OK] Listening found: %%A %%B %%C %%D %%E
)

if "!LISTEN_OK!"=="0" (
    echo [ERROR] Broker is NOT listening on port %TARGET_PORT%.
    echo [INFO] Trying second restart...
    taskkill /IM mosquitto.exe /F >nul 2>&1
    timeout /t 2 >nul
    start "Mosquitto Broker Retry" /min cmd /c ""%MOSQ_EXE%" -c "%MOSQ_CONF%" -v"
    timeout /t 4 >nul

    for /f "tokens=1,2,3,4,5" %%A in ('netstat -ano ^| findstr /R /C:":%TARGET_PORT% .*LISTENING"') do (
        set "LISTEN_OK=1"
        echo [OK] Listening found after retry: %%A %%B %%C %%D %%E
    )
)

if "!LISTEN_OK!"=="0" (
    echo [FATAL] Mosquitto still not listening on port %TARGET_PORT%.
    echo Check antivirus, another app blocking, or broken installation.
    pause
    exit /b 1
)
echo.

:: -------------------------------
:: Local TCP test using PowerShell
:: -------------------------------
echo [STEP] Testing localhost port connectivity...
powershell -NoProfile -Command "try { $r=Test-NetConnection -ComputerName 127.0.0.1 -Port 1883 -WarningAction SilentlyContinue; if($r.TcpTestSucceeded){exit 0}else{exit 1} } catch { exit 1 }"
if "%errorlevel%"=="0" (
    echo [OK] Localhost TCP test passed.
) else (
    echo [WARNING] Localhost TCP test failed.
)
echo.

:: -------------------------------
:: MQTT publish/subscribe test if tools exist
:: -------------------------------
echo [STEP] Running MQTT pub/sub test...
if exist "%MOSQ_SUB%" if exist "%MOSQ_PUB%" (
    if exist "%TEMP%\mqtt_sub_test.txt" del /f /q "%TEMP%\mqtt_sub_test.txt" >nul 2>&1

    start "MQTT_SUB_TEST" /min cmd /c ""%MOSQ_SUB%" -h 127.0.0.1 -p 1883 -t %TEST_TOPIC% > "%TEMP%\mqtt_sub_test.txt""
    timeout /t 3 >nul
    "%MOSQ_PUB%" -h 127.0.0.1 -p 1883 -t %TEST_TOPIC% -m %TEST_MSG% >nul 2>&1
    timeout /t 3 >nul

    findstr /C:"%TEST_MSG%" "%TEMP%\mqtt_sub_test.txt" >nul 2>&1
    if "%errorlevel%"=="0" (
        echo [OK] MQTT publish/subscribe test passed.
    ) else (
        echo [WARNING] MQTT pub/sub test did not confirm message.
        echo [INFO] Broker may still be running; this test can fail on some systems.
    )

    taskkill /FI "WINDOWTITLE eq MQTT_SUB_TEST" /F >nul 2>&1
) else (
    echo [INFO] mosquitto_sub.exe or mosquitto_pub.exe not found. Skipping MQTT pub/sub test.
)
echo.

:: -------------------------------
:: Ping target IP
:: -------------------------------
echo [STEP] Pinging auto detected IP %TARGET_IP% ...
ping -n 2 %TARGET_IP% >nul 2>&1
if "%errorlevel%"=="0" (
    echo [OK] Ping to %TARGET_IP% successful.
) else (
    echo [WARNING] Ping to %TARGET_IP% failed.
)
echo.

:: -------------------------------
:: Remote TCP test to target IP
:: -------------------------------
echo [STEP] Testing TCP connection to %TARGET_IP%:%TARGET_PORT% ...
powershell -NoProfile -Command "try { $r=Test-NetConnection -ComputerName '%TARGET_IP%' -Port %TARGET_PORT% -WarningAction SilentlyContinue; if($r.TcpTestSucceeded){exit 0}else{exit 1} } catch { exit 1 }"
if "%errorlevel%"=="0" (
    echo [OK] Remote TCP test to %TARGET_IP%:%TARGET_PORT% passed.
) else (
    echo [WARNING] Remote TCP test to %TARGET_IP%:%TARGET_PORT% failed.
    echo [INFO] This usually means:
    echo        1. Current IP changed
    echo        2. Client and server are on different network
    echo        3. Router or antivirus is blocking
)
echo.

:: -------------------------------
:: Service create / restart option
:: -------------------------------
echo [STEP] Ensuring Mosquitto service exists...
sc query mosquitto >nul 2>&1
if not "%errorlevel%"=="0" (
    sc create mosquitto binPath= "\"%MOSQ_EXE%\" -c \"%MOSQ_CONF%\"" start= auto >nul 2>&1
)

sc description mosquitto "Mosquitto MQTT Broker" >nul 2>&1
sc config mosquitto start= auto >nul 2>&1
net stop mosquitto >nul 2>&1
timeout /t 2 >nul
net start mosquitto >nul 2>&1

echo [INFO] Final port status:
netstat -ano | findstr :1883
echo.

echo ============================================================
echo   FIX PROCESS COMPLETE
echo ============================================================
echo.
echo [RESULT]
echo 1. Mosquitto config reset done
echo 2. Port 1883 cleanup done
echo 3. Firewall rule added
echo 4. Broker restart done
echo 5. Local tests done
echo.
echo [IMPORTANT]
echo Auto detected broker IP:
echo    %TARGET_IP%
echo.
echo Use this in your app/code:
echo    mqtt://%TARGET_IP%:1883
echo.
pause
endlocal
exit /b 0