@echo off
setlocal enabledelayedexpansion

:: Define variables for the fields to be updated
set "original_file=C:\ShopFloorConnect\FIT-MI_Server\webapps\wut\WEB-INF\conf\mi_server.ini"
set "backup_file=C:\ShopFloorConnect\FIT-MI_Server\webapps\wut\WEB-INF\conf\mi_server_backup.ini"
set "fsw_ip=10.233.113.141"
set "fsw_port=8080/tcdnc/services"

:: Get the computer's Fully Qualified Domain Name (FQDN) using PowerShell
for /f "usebackq delims=" %%A in (`powershell -NoProfile -Command "[System.Net.Dns]::GetHostEntry('localhost').HostName"`) do set "fqdn=%%A"

:: Display the FQDN for verification
echo Computer FQDN: !fqdn!


:: Create a temporary file for the updated content
set "temp_file=%original_file%.tmp"


:: Retry mechanism for deleting the temporary file
set "retry_count=0"
:retry_delete
if exist "%temp_file%" (
    echo Attempting to delete temporary file "%temp_file%"...
    del "%temp_file%"
    if errorlevel 1 (
        echo Error: Failed to delete temporary file "%temp_file%". Retrying...
        set /a retry_count+=1
        if %retry_count% GEQ 5 (
            echo Error: Unable to delete temporary file after 5 attempts.
            exit /b 1
        )
        timeout /t 2 >nul
        goto retry_delete
    )
)


:: Test temporary file creation
echo Creating temporary file...
echo Test > "%temp_file%"
if errorlevel 1 (
    echo Error: Failed to create temporary file "%temp_file%".
    echo Possible reasons:
    echo - File is locked or in use by another process.
    echo - Insufficient permissions to create files in the directory.
    echo - Disk space or file system issues.
    exit /b 1
)


:: Update the fields in the file
echo Updating the ini file...
(for /f "usebackq delims=" %%A in ("%original_file%") do (
    set "line=%%A"
    echo Processing line: !line! >nul
    :: Check for specific field names and update the entire line
    if /i "!line:local_ip =!" NEQ "!line!" (
        echo local_ip = !fqdn!
    ) else if /i "!line:fsw_ip =!" NEQ "!line!" (
        echo fsw_ip = %fsw_ip%
    ) else if /i "!line:fsw_port =!" NEQ "!line!" (
        echo fsw_port = %fsw_port%
    ) else if /i "!line:RxEndTimeout =!" NEQ "!line!" (
        echo RxEndTimeout = 6000
        echo.
    ) else (
        echo !line!
    )
)) > "%temp_file%"
if errorlevel 1 (
    echo Error: Failed to update the fields in the file.
    exit /b 1
)


:: Replace the original file with the updated file
move /y "%temp_file%" "%original_file%" >nul
if errorlevel 1 (
    echo Error: Failed to replace the original file with the updated file.
    exit /b 1
)

echo File updated successfully.

