@echo off
::
:: UltraDefrag - a powerful disk defragmenter for Windows.
::
:: show-report.cmd - displays a file fragmentation report.
::
:: Copyright (c) 2021 Green Gate Systems, LLC.
::
:: Synopsis:
::
::   show-report <drive_letter>
::

setlocal

set DRIVE_LETTER=%1

if "%DRIVE_LETTER%" equ "" (
    echo No drive letter specified!
    endlocal
    exit /B 1
)

set DRIVE_LETTER=%DRIVE_LETTER:~0,1%

if "%UD_INSTALL_DIR%" neq "" (
    pushd "%UD_INSTALL_DIR%"
) else (
    pushd .
)

:: enable generation of plain text reports
if not exist tmp mkdir tmp
call :generate_enable_text_reports_lua_script > tmp\enable-text-reports.lua || goto fail
lua5.1a tmp\enable-text-reports.lua || goto fail
del /q tmp\enable-text-reports.lua

:: generate the report
cd scripts
..\lua5.1a udreportcnv.lua ..\reports\fraglist_%DRIVE_LETTER%.luar || goto fail
cd ..

:: strip the byte order mark
call :generate_strip_bom_lua_script > tmp\strip-bom.lua || goto fail
lua5.1a tmp\strip-bom.lua reports\fraglist_%DRIVE_LETTER%.txt || goto fail
del /q tmp\strip-bom.lua

:: display the report
type reports\fraglist_%DRIVE_LETTER%.txt

:success
popd
endlocal
exit /B 0

:fail
popd
endlocal
exit /B 1

:generate_enable_text_reports_lua_script
    echo -- read the entire configuration file
    echo f = assert(io.open("conf\\options.lua", "r"))
    echo contents = f:read("*all")
    echo f:close()
    echo.
    echo -- enable generation of plain text reports
    echo new_contents = string.gsub(contents,"produce_plain_text_report%%s*=%%s*%%d+","produce_plain_text_report = 1")
    echo.
    echo -- save the updated file contents
    echo f = assert(io.open("conf\\options.lua", "w"))
    echo f:write(new_contents)
    echo f:close()
exit /B 0

:generate_strip_bom_lua_script
    echo -- read the entire file
    echo f = assert(io.open(arg[1], "r"))
    echo contents = f:read("*all")
    echo f:close()
    echo.
    echo -- strip the byte order mark
    echo new_contents = string.sub(contents,4)
    echo.
    echo -- save the updated file contents
    echo f = assert(io.open(arg[1], "w"))
    echo f:write(new_contents)
    echo f:close()
exit /B 0
