function defaultUsername = pGetDefaultUsername()
; %#ok Undocumented
% Get the username of the user who started MATLAB.

% Copyright 2009-2020 The MathWorks, Inc.

persistent username
if ~isempty(username)
    defaultUsername = username;
    return
end

if system_dependent('isdmlworker')
    % dmlworkers always use this value
    username = getenv('PARALLEL_SERVER_USERNAME');
else
    if com.mathworks.matlab.environment.context.Util.isMATLABOnline() && parallel.internal.mwa.isLoggedIn()
        % This branch will only be used by MO and MOS and when MWA is integrated with the stack 
        user = parallel.internal.mwa.ensureLoggedIn();
        username = user.getUsername();
    else
        % Note: this branch is used to support Desktop MATLAB and MOS when MWA is not integrated with the stack
        defaultUserIdentity = com.mathworks.toolbox.distcomp.mjs.auth.credentials.UserIdentity.createDefaultUserIdentity();
        username = char(defaultUserIdentity.getSimpleUsername());
    end
end

defaultUsername = username;


