@echo off
setlocal EnableDelayedExpansion

if "%~1"=="" (
    set "DISKS=C"
    set "THRESHOLD=90"
) else (
    set "DISKS=%~1"
    if "%~2"=="" (
        set "THRESHOLD=90"
    ) else (
        set "THRESHOLD=%~2"
    )
)

for /f "tokens=2 delims==" %%a in ('powershell -Command "Get-Date -Format 'yyyy-MM-dd_HH-mm-ss'"') do set TS=%%a
set "RAPORT=disk_report_%TS%.txt"

echo ======================================== > "%RAPORT%"
echo MONITOR ZAJETOSCI DYSKOW >> "%RAPORT%"
echo Data: %DATE% %TIME% >> "%RAPORT%"
echo Próg alertu: %THRESHOLD%% >> "%RAPORT%"
echo ======================================== >> "%RAPORT%"
echo. >> "%RAPORT%"

echo ========================================
echo MONITOR ZAJETOSCI DYSKOW
echo Data: %DATE% %TIME%
echo Próg alertu: %THRESHOLD%%
echo ========================================

:check_disk
for %%D in (%DISKS%) do (
    set "DYSK=%%D"
    call :check_single_disk
)

echo ========================================
echo Podsumowanie: !ALERT_COUNT! alertow
echo ========================================

echo. >> "%RAPORT%"
echo Podsumowanie: !ALERT_COUNT! alertow >> "%RAPORT%"

type "%RAPORT%"
echo.
echo Raport zapisany: %RAPORT%

endlocal
exit /b 0

:check_single_disk
set "DRIVE_LETTER=!DYSK!:"

for /f "tokens=2" %%A in ('powershell -Command "Get-PSDrive -Name !DYSK! 2^>nul ^| Select-Object -ExpandProperty Used"') do (
    set "UZYTE=%%A"
)

for /f "tokens=2" %%A in ('powershell -Command "Get-PSDrive -Name !DYSK! 2^>nul ^| Select-Object -ExpandProperty Free"') do (
    set "WOLNE=%%A"
)

if not defined UZYTE (
    echo Dysk !DYSK!: BLAD - nie mozna odczytac danych
    exit /b 0
)

set /a CALKOWITE=UZYTE + WOLNE
set /a PROCENT=UZYTE * 100 / CALKOWITE

call :format_bytes USED_STR UZYTE
call :format_bytes FREE_STR WOLNE
call :format_bytes TOTAL_STR CALKOWITE

echo.
echo Dysk !DYSK!:
echo   Uzyte:  !USED_STR!
echo   Wolne:  !FREE_STR!
echo   Calkowite: !TOTAL_STR!
echo   Zajetosc: !PROCENT!%%
echo   Wizualizacja:

set "BARS="
set /a BARS_COUNT=PROCENT / 2
for /l %%B in (1,1,!BARS_COUNT!) do set "BARS=!BARS!#"
for /l %%B in (!BARS_COUNT!,1,50) do set "BARS=!BARS!-"

if !PROCENT! GEQ %THRESHOLD% (
    echo   [!BARS!] 
    echo   [ALERT: Przekroczono prog !THRESHOLD!%%!]
    set /a ALERT_COUNT+=1
) else (
    echo   [!BARS!]
)

echo   Dysk !DYSK!: !PROCENT!%% zajecie >> "%RAPORT%"
if !PROCENT! GEQ %THRESHOLD% (
    echo   [ALERT] >> "%RAPORT%"
)
exit /b 0

:format_bytes
setlocal
set "SIZE=%~2"
set "RESULT="

if %SIZE% GEQ 1099511627776 (
    set /a TB=%SIZE% / 1099511627776
    set "RESULT=!TB! TB"
) else if %SIZE% GEQ 1073741824 (
    set /a GB=%SIZE% / 1073741824
    set "RESULT=!GB! GB"
) else if %SIZE% GEQ 1048576 (
    set /a MB=%SIZE% / 1048576
    set "RESULT=!MB! MB"
) else if %SIZE% GEQ 1024 (
    set /a KB=%SIZE% / 1024
    set "RESULT=!KB! KB"
) else (
    set "RESULT=%SIZE% B"
)
endlocal & set "%~1=%RESULT%"
exit /b 0