@echo off
::
:: UltraDefrag - a powerful disk defragmenter for Windows.
::
:: setenv.cmd - sets the UltraDefrag specific environment
::              variables according to the user preferences.
::
:: Copyright (c) 2021 Green Gate Systems, LLC.
::
:: Synopsis:
::
::   setenv
::

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

:: extract preferences from the main configuration file
if not exist tmp mkdir tmp
call :generate_extract_preferences_lua_script > tmp\extract_preferences.lua || goto fail
lua5.1a tmp\extract_preferences.lua || goto fail

:: set the environment variables
call tmp\set_environment.cmd

:success
del /q tmp\extract_preferences.lua
del /q tmp\set_environment.cmd
popd
exit /B 0

:fail
del /q tmp\extract_preferences.lua
del /q tmp\set_environment.cmd
popd
exit /B 1

:generate_extract_preferences_lua_script
    echo function save_preference(f, name)
    echo     local value = os.getenv(name)
    echo     if not value then value = "" end
    echo     f:write("set " .. name .. "=" .. value .. "\n")
    echo end
    echo.
    echo -- read the main configuration file
    echo dofile("conf\\options.lua")
    echo.
    echo -- generate the set_environment.cmd script
    echo f = assert(io.open("tmp\\set_environment.cmd", "w"))
    echo f:write("@echo off\n")
    echo save_preference(f, "UD_CLEAN_TEMP_FILES")
    echo save_preference(f, "UD_IN_FILTER")
    echo save_preference(f, "UD_EX_FILTER")
    echo save_preference(f, "UD_FRAGMENT_SIZE_THRESHOLD")
    echo save_preference(f, "UD_FILE_SIZE_THRESHOLD")
    echo save_preference(f, "UD_FRAGMENTS_THRESHOLD")
    echo save_preference(f, "UD_SORTING")
    echo save_preference(f, "UD_SORTING_ORDER")
    echo save_preference(f, "UD_OPTIMIZER_FILE_SIZE_THRESHOLD")
    echo save_preference(f, "UD_FRAGMENTATION_THRESHOLD")
    echo --save_preference(f, "UD_TIME_LIMIT")
    echo --save_preference(f, "UD_REFRESH_INTERVAL")
    echo --save_preference(f, "UD_DISABLE_REPORTS")
    echo --save_preference(f, "UD_DBGPRINT_LEVEL")
    echo --save_preference(f, "UD_LOG_FILE_PATH")
    echo save_preference(f, "UD_DRY_RUN")
    echo f:close()
exit /B 0
