@echo off
title Tox DHT Bootstrap Auto-Setup
setlocal enabledelayedexpansion
taskkill /f /im DHT_bootstrap.exe > nul 2>&1

set PORT=33445
set CONFIG_FILE=config.ini
set TEMP_OUTPUT=tox_output.txt
del "%TEMP_OUTPUT%" 2>nul

echo ========================================
echo Tox DHT Bootstrap Auto-Setup
echo ========================================
echo.

echo Get external IP..

for /f "tokens=2 delims=: " %%a in ('nslookup myip.opendns.com. resolver1.opendns.com 2^>NUL ^| find "Address:"') do set EXTERNAL_IP=%%a

if not defined EXTERNAL_IP (
    echo Error:  Cant get IP
    pause
    exit /b 1
)

echo External IP: %EXTERNAL_IP%
echo.

start /b DHT_bootstrap.exe --port %PORT% > "%TEMP_OUTPUT%" 2>&1

timeout /t 3 /nobreak > nul
taskkill /f /im DHT_bootstrap.exe > nul 2>&1

echo Read Public Key...

for /f "usebackq delims=" %%a in ("PUBLIC_ID.txt") do (
    set PUBLIC_KEY=%%a
    goto KEY_READ
)
:KEY_READ
if not defined PUBLIC_KEY (
    echo Error: Cant get Public Key from DHT_bootstrap
    type "%TEMP_OUTPUT%"
    del "%TEMP_OUTPUT%" 2>nul
    taskkill /f /im DHT_bootstrap.exe > nul 2>&1
    pause
    exit /b 1
)

echo Public: %PUBLIC_KEY%
echo.


taskkill /f /im DHT_bootstrap.exe > nul 2>&1

if %errorlevel% equ 0 (
    echo DHT_bootstrap success killed
) else (
    echo DHT_bootstrap not found
)

del "%TEMP_OUTPUT%" 2>nul
echo.

(
echo bootstrap_nodes = ^(
echo   { 
echo     address = "%EXTERNAL_IP%"
echo     port = %PORT%
echo     public_key = "%PUBLIC_KEY%"
echo   }
echo ^)
) > "%CONFIG_FILE%"

if exist "%CONFIG_FILE%" (
    echo %CONFIG_FILE% success created
) else (
    echo Error: Cant create %CONFIG_FILE%
    pause
    exit /b 1
)
echo.


if not exist "%CONFIG_FILE%" (
    echo Error: Cant find %CONFIG_FILE% 
    pause
    exit /b 1
)

DHT_bootstrap.exe --config config.ini

