function polyspacesetup(varargin)
%POLYSPACESETUP - manage installation of Polyspace Simulink plug-in in MATLAB
%
%   POLYSPACESETUP('install', 'polyspaceFolder', POLYSPACEFOLDER) installs 
%   Polyspace plug-in located in the folder POLYSPACEFOLDER on your current
%   version of MATLAB.
%
%   POLYSPACESETUP('install', 'polyspaceFolder', POLYSPACEFOLDER, 'silent', ISSILENT)
%   installs Polyspace without confirmation messages if ISSILENT is set to true.
%   When ISSILENT is false (default), the installation shows confirmation messages.
%
%   POLYSPACESETUP('uninstall') removes the current installation of
%   Polyspace plug-in from your current version of MATLAB.
%
%   POLYSPACESETUP('showpolyspacefolders') lists all Polyspace plug-in 
%   folders installed with your current version of MATLAB.

% Copyright 2020 The MathWorks, Inc.

parserObj = inputParser;
parserObj.addOptional('action', 'install', @(x) (isstring(x) && isscalar(x)) || ischar(x));
parserObj.addParameter('polyspaceFolder', '', @(x) (isstring(x) && isscalar(x)) || ischar(x));
parserObj.addParameter('silent', false, @islogical);
parserObj.parse(varargin{:});

action = char(parserObj.Results.action);
polyspaceFolder = parserObj.Results.polyspaceFolder;
isSilent = parserObj.Results.silent;

if isempty(polyspaceFolder) && exist('polyspaceroot') ~= 0 %#ok<EXIST>
    polyspaceFolder = polyspaceroot;
end

if isfolder(polyspaceFolder)
    psSetupPath = fullfile(polyspaceFolder, 'toolbox', 'polyspace', 'pscore', 'pscore');
    if isfolder(psSetupPath)
        originalDir = pwd;
        try
            cd(psSetupPath);
            polyspacesetup(action, 'silent', isSilent);
            % Cannot use onCleanup due to clear classes done by called function
            cd(originalDir);
        catch ME
            cd(originalDir);
            rethrow(ME);
        end
    else
        error('pslink:badMATLABVersion',...
            'The provided path to Polyspace installation is not valid.')
    end
else
    error('pslink:badMATLABVersion',...
        'The provided path to Polyspace installation does not exist.')
end
end
