%D \module
%D   [       file=m-document,
%D        version=2025.11.13,
%D          title=\CONTEXT\ Extra Modules,
%D       subtitle=Document features,
%D         author=Hans Hagen,
%D           date=\currentdate,
%D      copyright={PRAGMA ADE \& \CONTEXT\ Development Team}]
%C
%C This module is part of the \CONTEXT\ macro||package and is
%C therefore copyrighted by \PRAGMA. See mreadme.pdf for
%C details.

%D Here we can collect (if I remember that this file exists) features that are
%D disputable and/or don't belong on the core. I leave it to others (wiki) to
%D document this.

\startmodule[document]

% \setupsystem[resultfile=oof]
% \setupsystem[resultfile=foo]
%
% \startluacode
%     moduledata.document.setupoutputfilename("foo")
% \stopluacode
%
% \starttext
%     test
% \stoptext

\startluacode
moduledata.document = moduledata.document or { }

local result = false

function moduledata.document.setoutputfilename(name)
    if not result then
        luatex.wrapup(
            function()
                if os.remove(result) and
                   os.rename(tex.jobname .. ".pdf",result) then
                    logs.report("system")
                    logs.report("system","output file renamed to %a",result)
                    logs.report("system")
                end
            end
        )
    end
    if name ~= "" then
        result = file.addsuffix(name,"pdf")
    end
end
\stopluacode

\appendtoks
    \ifempty{\systemparameter{resultfile}}\else
        \ctxlua{moduledata.document.setoutputfilename("\lastnamedcs")}
    \fi
\to \everysetupsystem

\stopmodule

