@echo off
setlocal

:: --------- Setup Log ---------
set "LOG_FILE=cosmic_setup.log"
echo [%DATE% %TIME%] Starting script... > "%LOG_FILE%"

:: --------- Define Paths ---------
set "CURRENT_DIR=%~dp0"
if "%CURRENT_DIR:~-1%"=="\" set "CURRENT_DIR=%CURRENT_DIR:~0,-1%"

set "SOUNDS_DIR=%CURRENT_DIR%\cosmic rage\worlds\cosmic rage\sounds"
set "REPO_URL=http://nathantech.net:3000/CosmicRage/CosmicRageSounds"
set "REPO_SUBFOLDER=ogg"
set "GIT_PORTABLE=%CURRENT_DIR%\gitportable\bin\git.exe"

echo [%DATE% %TIME%] Script location: %CURRENT_DIR% >> "%LOG_FILE%"
echo [%DATE% %TIME%] Sounds directory: %SOUNDS_DIR% >> "%LOG_FILE%"

:: --------- Check for Git Installation ---------
set "GIT_CMD=git"
where git >nul 2>&1
if errorlevel 1 (
    if not exist "%GIT_PORTABLE%" (
        echo [%DATE% %TIME%] ERROR: No valid Git installation or GitPortable found. >> "%LOG_FILE%"
        echo ERROR: Git is not installed, and GitPortable is missing.
        pause
        exit /b
    ) else (
        set "GIT_CMD=%GIT_PORTABLE%"
        echo [%DATE% %TIME%] Using GitPortable: %GIT_CMD% >> "%LOG_FILE%"
    )
) else (
    echo [%DATE% %TIME%] Using system Git: %GIT_CMD% >> "%LOG_FILE%"
)

:: --------- Download sounds using partial clone + sparse checkout ---------
echo [%DATE% %TIME%] Downloading sound files using Git sparse clone... >> "%LOG_FILE%"
rd /s /q "%SOUNDS_DIR%" >nul 2>&1

"%GIT_CMD%" clone --depth=1 --filter=blob:none --sparse "%REPO_URL%" "%SOUNDS_DIR%"
if errorlevel 1 (
    echo [%DATE% %TIME%] ERROR: Git clone failed. >> "%LOG_FILE%"
    echo ERROR: Failed to clone repo. Check network or Git version.
    pause
    exit /b
)

pushd "%SOUNDS_DIR%"
"%GIT_CMD%" sparse-checkout set "%REPO_SUBFOLDER%" >> "%LOG_FILE%" 2>&1
if not exist "%SOUNDS_DIR%\%REPO_SUBFOLDER%" (
    echo [%DATE% %TIME%] ERROR: Failed to checkout sparse folder. >> "%LOG_FILE%"
    echo ERROR: Could not pull sparse folder. Check folder name or repo.
    pause
    popd
    exit /b
)
popd
echo [%DATE% %TIME%] Sounds successfully cloned. >> "%LOG_FILE%"

:: --------- Finish ---------
echo [%DATE% %TIME%] Script completed successfully. >> "%LOG_FILE%"
echo Setup complete.
pause
exit /b
