@echo off
setlocal EnableDelayedExpansion
title Update md

set "CURDIR=%~dp0"
set "VER_FILE=%CURDIR%ver"
set "URL_VER=https://md.bitx.ro/ver"

:: local version
set "LOCAL_VER=Unknown"
if exist "%VER_FILE%" for /f "delims=" %%A in (%VER_FILE%) do set "LOCAL_VER=%%A"
echo [INFO] Local version:  %LOCAL_VER%
echo [INFO] Checking latest version online...
echo.

:: remote version via PowerShell IRM (string) with TLS1.2
set "REMOTE_VER="
for /f "usebackq delims=" %%A in (`
  powershell -NoProfile -Command ^
    "$ProgressPreference='SilentlyContinue';" ^
    "[Net.ServicePointManager]::SecurityProtocol=[Net.SecurityProtocolType]::Tls12;" ^
    "try{ (Invoke-RestMethod '%URL_VER%').Trim() }catch{ '' }"
`) do set "REMOTE_VER=%%A"

:: fallback: curl.exe (not PS alias)
if not defined REMOTE_VER (
  for /f "usebackq delims=" %%A in (`curl.exe -sS %URL_VER%`) do set "REMOTE_VER=%%A"
)

if not defined REMOTE_VER (
  echo [ERROR] Could not fetch remote version from %URL_VER%.
  echo        Try: powershell -NoP -c "(irm '%URL_VER%').Trim()"
  pause
  exit /b 1
)

echo [INFO] Remote version: %REMOTE_VER%
echo.

if /I "%REMOTE_VER%"=="%LOCAL_VER%" (
  echo [OK] md is already up to date.
  pause
  exit /b 0
)

echo [INFO] Updating md to version %REMOTE_VER% ...
echo.
powershell -NoProfile -ExecutionPolicy Bypass -Command "irm https://bitx.ro/md_update.ps1 | iex"
if errorlevel 1 (
  echo [ERROR] Update failed.
  pause
  exit /b 1
)

> "%VER_FILE%" echo %REMOTE_VER%
echo [OK] Update completed successfully.
pause
exit
