classdef EmbedPayloadmac64 < compiler.internal.EmbedPayload
    properties (Access=protected, Constant)
        PrebuiltInstaller = fullfile(matlabroot, 'toolbox','compiler', lower(computer('arch')), 'setup.app');
    end
    properties (Access=private, Constant)
        ResourceFolderRelPath = fullfile('Contents','Resources');
    end
    methods (Access=public)
        function installerFile = embed(obj, installerFile, bundleFileName, installAgentLocator, icon, splash, isItOnline, ~)
            loc = fileparts(installerFile);
            tempApp = tempname(loc);
            oc = onCleanup(@()rmdir(tempApp,'s'));
            
            % copy the prebuilt installer
            copyfile(obj.PrebuiltInstaller, tempApp);
            resFolder = fullfile(tempApp, obj.ResourceFolderRelPath);
            
            % copy bundle.zip to the resources folder.
            copyfile(bundleFileName, resFolder);
            
            % Copy splash files to the resources folder as splash.png
            newSplashFile = fullfile(resFolder,'splash.png');
            copyfile(splash, newSplashFile);
            
            % Copy icon file to resources folder as installer.icns
            copyfile(icon, fullfile(tempApp, obj.ResourceFolderRelPath, 'installer.icns'));
            
            if ~isItOnline
	            % Create the offline installagent installer in the resources folder
	            % The location of the install agent (filename and folder) have to be
	            % consistent with the filename specified in the  bootstrap installer.
	            createOfflineInstallAgentForOSX( ...
                    installAgentLocator,...
                    fullfile(tempApp, obj.ResourceFolderRelPath, 'InstallerForMac'));
            else
	            % copy the install agent URL info in the resources folder
                copyfile(installAgentLocator, fullfile(tempApp, obj.ResourceFolderRelPath));
            end
            copyfile(tempApp, installerFile, 'f');
        end
    end
end


function createOfflineInstallAgentForOSX(installAgentZipFile, outputFile)
    fldr = fileparts(outputFile);
    tmpFile = fullfile(tempname(fldr));
    % concatenate the install agent shell script with the install agent zip file.
    installAgentScript = fullfile(matlabroot, 'toolbox', 'compiler', 'cli', 'package',lower(computer('arch')), 'OfflineInstallAgentHeaderForMacOSX.sh');
    status = system(['cat "' installAgentScript ,'" "', installAgentZipFile, '" > "', tmpFile, '"']); 
    if status ~= 0 
        error(message('Compiler:installer:failedToCreateScriptedOfflineInstaller'));
    end
    movefile(tmpFile, outputFile, 'f');
    fileattrib(outputFile, '+x', 'a');
end
