function [success,problem,reportStr] = configureToolchain...
        (h, actionstring, lBuildLogger, runMatlabScriptOnly)

%   Copyright 2014-2020 The MathWorks, Inc.

actionstrings = {'DoToolchainSetup', 'DoToolchainCleanup'};
action = validatestring(actionstring, actionstrings);

if strcmp(action, 'DoToolchainSetup')
    if runMatlabScriptOnly
        fcnsToRun = {'MATLABSetup'};
    else
        fcnsToRun = {'MATLABSetup', 'ShellSetup'};
    end
else % DoToolchainCleanup
    if runMatlabScriptOnly
        fcnsToRun = {'MATLABCleanup'};
    else
        fcnsToRun = {'MATLABCleanup', 'ShellCleanup'};
    end
end

reportStr = '';
success = true;
problem = '';

for i=1:length(fcnsToRun)
    [toolSuccess, toolProblem, toolReport] = ...
        i_configureProperty(h, lBuildLogger, fcnsToRun{i});

    problem = [problem toolProblem];
    reportStr = [reportStr toolReport newline]; %#ok<*AGROW>
    success = success && toolSuccess;
    
end


function [success, toolProblem, toolReport] = i_configureProperty(h, lBuildLogger, prop)

success=true;
toolProblem = '';
toolReport = '';

if ~isprop( h, prop )
    error( message( 'coder_compile:toolchain:NotAProperty', prop, class( h ) ) )
end
cmdSetupCleanup = h.(prop);
if numel( cmdSetupCleanup )==0
    return
end
% Invoke setup/cleanup command
toolReport = [ '### Validation of "', prop, '"', newline ];
invokeMatlabScript = any( strcmp( prop, { 'MATLABSetup', 'MATLABCleanup' } ) );
invokeShellScript = any( strcmp( prop, { 'ShellSetup', 'ShellCleanup' } ) );

for i = 1:numel( cmdSetupCleanup )
    toolReport = [toolReport, 'Validating command: ', cmdSetupCleanup{i}, newline];
    if invokeMatlabScript
        % Evaluate the MATLAB command
        try
            evalResult = evalc(cmdSetupCleanup{i});
            addToBuildLog(lBuildLogger, evalResult);
        catch exc
            success = false;
            toolProblem = [ 'Command "', cmdSetupCleanup{ i }, '" threw an error: ', exc.message(), newline ];
            toolReport = [ toolReport, toolProblem ];
        end
    elseif invokeShellScript
        if h.isAttribute( 'RequiresBatchFile' )
            % This shell setup will be done in the
            % batch file.
            continue
        else
            % Invoke the system command on the system
            % command.
            [status, result] = rtw.system(cmdSetupCleanup{i});
            addToBuildLog(lBuildLogger, result);
            success = (status==0);
            if ~success && ~isempty(strtrim(result))
                throw(result);
            end
        end
    end
    if success
        toolReport = [ toolReport, 'Passed.', newline ];
    end
end


