@echo off
setlocal EnableExtensions EnableDelayedExpansion

rem ============================================================
rem  Installer.bat  — English bootstrap
rem  Folder must be “empty” except allowed:
rem    - dependencies\
rem    - .minecraft\
rem    - .tlauncher\
rem    - (this .bat, desktop.ini, Thumbs.db)
rem  Bundled structure expected: dependencies\curl\ and dependencies\7z\
rem  Steps:
rem    1) Gate: clean folder check
rem    2) Ensure deps paths; download base.7z via local curl; extract via local 7z; delete archive
rem    3) Download all mods listed at ?dir=mods into .minecraft\mods using local curl
rem    4) Clean dependencies\temp and create StartLegacyLauncher.bat
rem ============================================================

rem Always operate from the script’s directory
cd /d "%~dp0"

set "ALLOWED_DIR1=dependencies"
set "ALLOWED_DIR2=.minecraft"
set "ALLOWED_DIR3=.tlauncher"
set "NOT_EMPTY=0"

echo.
echo [INFO] Checking folder contents:
echo        %CD%
echo.

rem --- Check directories (include hidden/system) ---
for /f "delims=" %%D in ('dir /b /a:d') do (
    if /I not "%%D"=="%ALLOWED_DIR1%" if /I not "%%D"=="%ALLOWED_DIR2%" if /I not "%%D"=="%ALLOWED_DIR3%" (
        set "NOT_EMPTY=1"
        echo [WARN] Unexpected directory found: "%%D"
    )
)

rem --- Check files (exclude this script and common system files) ---
for /f "delims=" %%F in ('dir /b /a:-d') do (
    if /I not "%%F"=="%~nx0" (
        if /I not "%%F"=="desktop.ini" if /I not "%%F"=="Thumbs.db" (
            set "NOT_EMPTY=1"
            echo [WARN] Unexpected file found: "%%F"
        )
    )
)

if "%NOT_EMPTY%"=="1" (
    echo.
    echo [ERROR] This folder is not empty according to the installer rules.
    echo         Please move the installer to a new empty folder
    echo         or remove the unexpected items listed above.
    echo.
    pause
    exit /b 1
)

echo [OK] Folder is clean (only allowed items present).
echo.

rem --- Paths to bundled tools and temp ---
set "DROOT=%CD%"
set "DDEPS=%CD%\dependencies"
set "D7Z=%DDEPS%\7z"
set "DCURL=%DDEPS%\curl"
set "DTEMP=%DDEPS%\temp"

rem --- Check bundled tools presence ---
if exist "%DCURL%\curl.exe" (
    echo [INFO] Found: dependencies\curl\curl.exe
) else (
    echo [ERROR] Missing dependencies\curl\curl.exe. Please ensure the bundled files are present.
    pause
    exit /b 2
)

if exist "%D7Z%\7z.exe" (
    echo [INFO] Found: dependencies\7z\7z.exe
) else (
    echo [ERROR] Missing dependencies\7z\7z.exe. Please ensure the bundled files are present.
    pause
    exit /b 2
)

if not exist "%DTEMP%" (
    md "%DTEMP%" 2>nul
    if errorlevel 1 (
        echo [ERROR] Could not create temp folder: "%DTEMP%"
        pause
        exit /b 2
    )
)

echo.

goto :STEP_BASE

:STEP_BASE
rem ============================================================
rem  STEP: Download base.7z -> Extract to script root -> Delete base.7z
rem ============================================================
set "BASE_URL=https://download.chungusreborn.mlcz.pl/?file=base/base.7z"
set "BASE_7Z=%DTEMP%\base.7z"

echo [INFO] Downloading base.7z via local curl...
call :CURL_DOWNLOAD "%BASE_URL%" "%BASE_7Z%" || (
    echo [ERROR] Download failed. Check your connection and try again.
    pause
    exit /b 3
)

echo [INFO] Extracting base.7z to:
echo        %DROOT%
echo.
"%D7Z%\7z.exe" x -y -o"%DROOT%" "%BASE_7Z%"
set "ZRET=%ERRORLEVEL%"

if not "%ZRET%"=="0" (
    echo [ERROR] Extraction failed. 7z exit code: %ZRET%
    echo         File left at: %BASE_7Z%
    pause
    exit /b 4
)

if exist "%BASE_7Z%" (
    del /q "%BASE_7Z%" >nul 2>&1
    if exist "%BASE_7Z%" (
        echo [WARN] Could not delete: %BASE_7Z%
    ) else (
        echo [INFO] Removed downloaded archive: base.7z
    )
)

echo.
echo [DONE] base.7z downloaded, extracted, and cleaned up.
echo.

goto :STEP_MODS

:STEP_MODS
rem ============================================================
rem  STEP: Download all mods from ?dir=mods into .minecraft\mods
rem  - Fetch index HTML with curl
rem  - Use PowerShell regex to extract "?file=mods/..." links
rem  - Download each file into ".minecraft\mods"
rem ============================================================

set "MODS_INDEX_URL=https://download.chungusreborn.mlcz.pl/?dir=mods"
set "MODS_INDEX_HTML=%DTEMP%\mods_index.html"
set "MODS_LIST_TXT=%DTEMP%\mods_list.txt"
set "DMODSROOT=%CD%\.minecraft\mods"

if not exist "%CD%\.minecraft" md "%CD%\.minecraft" >nul 2>&1
if not exist "%DMODSROOT%" md "%DMODSROOT%" >nul 2>&1

echo [INFO] Fetching mods index page...
call :CURL_DOWNLOAD "%MODS_INDEX_URL%" "%MODS_INDEX_HTML%" || (
    echo [ERROR] Could not fetch mods index.
    pause
    exit /b 5
)

echo [INFO] Parsing links from mods index (PowerShell)...
powershell -NoLogo -NoProfile -ExecutionPolicy Bypass -Command ^
  "$h = Get-Content -Raw -LiteralPath '%MODS_INDEX_HTML%';" ^
  "$m = [regex]::Matches($h, '\?file=mods\/[^""''\s<>]+');" ^
  "$urls = $m | ForEach-Object { 'https://download.chungusreborn.mlcz.pl/' + $_.Value };" ^
  "$urls | Sort-Object -Unique | ForEach-Object { $_ + '|' + (($_ -split '/')[-1]) } | Out-File -Encoding ASCII '%MODS_LIST_TXT%'"

if errorlevel 1 (
    echo [ERROR] Failed to parse mods list.
    pause
    exit /b 6
)

if not exist "%MODS_LIST_TXT%" (
    echo [ERROR] Mods list file not created.
    pause
    exit /b 6
)

for /f "usebackq tokens=1,2 delims=|" %%A in ("%MODS_LIST_TXT%") do (
    set "URL=%%~A"
    set "FNAME=%%~B"
    if not defined FNAME (
        echo [WARN] Skipping malformed line.
    ) else (
        echo [INFO] Downloading mod: !FNAME!
        call :CURL_DOWNLOAD "!URL!" "%DMODSROOT%\!FNAME!" || (
            echo [WARN] Failed to download: !FNAME!
        )
    )
)

rem ============================================================
rem  NEW STEP: Clean dependencies\temp and create StartLegacyLauncher.bat
rem ============================================================
echo.
echo [CLEANUP] Clearing "dependencies\temp"...
if exist "%DTEMP%" (
    rmdir /s /q "%DTEMP%" >nul 2>&1
)
md "%DTEMP%" >nul 2>&1
if exist "%DTEMP%" (
    echo [OK] Temp folder reset: "%DTEMP%"
) else (
    echo [WARN] Could not recreate: "%DTEMP%"
)

echo [INFO] Creating launcher batch: "Start.bat"
set "LAUNCH_BAT=%DROOT%\Start.bat"
> "%LAUNCH_BAT%" echo @ECHO OFF
>>"%LAUNCH_BAT%" echo set APPDATA=%%~dp0
>>"%LAUNCH_BAT%" echo SET BINDIR=%%~dp0
>>"%LAUNCH_BAT%" echo CD /D "%%BINDIR%%"
>>"%LAUNCH_BAT%" echo java -Xincgc -Xmx128M -jar LegacyLauncher.jar
>>"%LAUNCH_BAT%" echo exit

if exist "%LAUNCH_BAT%" (
    echo [OK] Created: "%LAUNCH_BAT%"
) else (
    echo [ERROR] Failed to create launcher .bat
)

echo.
echo [DONE] Mods download step completed. Files are in:
echo        %DMODSROOT%
echo.
pause
exit /b 0


rem ============================================================
rem  FUNCTIONS
rem ============================================================

rem  :CURL_DOWNLOAD  (URL, OUT_PATH)
rem  Uses local dependencies\curl\curl.exe with CA bundle if present
:CURL_DOWNLOAD
setlocal
set "URL=%~1"
set "OUT=%~2"

if not exist "%~dp2" md "%~dp2" >nul 2>&1

echo [INFO] curl: %URL%
echo          -> %OUT%

set "CACERT_ARG="
if exist "%DCURL%\curl-ca-bundle.crt" (
    set "CACERT_ARG=--cacert "%DCURL%\curl-ca-bundle.crt""
)

"%DCURL%\curl.exe" -fL --retry 3 --retry-delay 2 --connect-timeout 20 %CACERT_ARG% -o "%OUT%" "%URL%"
set "RC=%ERRORLEVEL%"

if %RC% NEQ 0 (
    echo [ERR] curl returned %RC%.
    endlocal & exit /b %RC%
)

for %%S in ("%OUT%") do (
    if %%~zS GTR 0 (
        echo [OK] Downloaded: "%%~fS" (%%~zS bytes)
        endlocal & exit /b 0
    )
)

echo [ERR] Downloaded file is empty or missing.
endlocal & exit /b 1
