"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
const _7zip_bin_1 = require("7zip-bin");
const builder_util_1 = require("builder-util");
const fs_1 = require("builder-util/out/fs");
const fs_extra_1 = require("fs-extra");
const promises_1 = require("fs/promises");
const path = require("path");
const appInfo_1 = require("../appInfo");
const core_1 = require("../core");
const errorMessages = require("../errorMessages");
const appBuilder_1 = require("../util/appBuilder");
const bundledTool_1 = require("../util/bundledTool");
const macosVersion_1 = require("../util/macosVersion");
const pathManager_1 = require("../util/pathManager");
const LinuxTargetHelper_1 = require("./LinuxTargetHelper");
const tools_1 = require("./tools");
class FpmTarget extends core_1.Target {
    constructor(name, packager, helper, outDir) {
        super(name, false);
        this.packager = packager;
        this.helper = helper;
        this.outDir = outDir;
        this.options = { ...this.packager.platformSpecificBuildOptions, ...this.packager.config[this.name] };
        this.scriptFiles = this.createScripts();
    }
    async createScripts() {
        const defaultTemplatesDir = pathManager_1.getTemplatePath("linux");
        const packager = this.packager;
        const templateOptions = {
            // old API compatibility
            executable: packager.executableName,
            sanitizedProductName: packager.appInfo.sanitizedProductName,
            productFilename: packager.appInfo.productFilename,
            ...packager.platformSpecificBuildOptions,
        };
        function getResource(value, defaultFile) {
            if (value == null) {
                return path.join(defaultTemplatesDir, defaultFile);
            }
            return path.resolve(packager.projectDir, value);
        }
        return await Promise.all([
            writeConfigFile(packager.info.tempDirManager, getResource(this.options.afterInstall, "after-install.tpl"), templateOptions),
            writeConfigFile(packager.info.tempDirManager, getResource(this.options.afterRemove, "after-remove.tpl"), templateOptions),
        ]);
    }
    checkOptions() {
        return this.computeFpmMetaInfoOptions();
    }
    async computeFpmMetaInfoOptions() {
        var _a;
        const packager = this.packager;
        const projectUrl = await packager.appInfo.computePackageUrl();
        const errors = [];
        if (projectUrl == null) {
            errors.push("Please specify project homepage, see https://electron.build/configuration/configuration#Metadata-homepage");
        }
        const options = this.options;
        let author = options.maintainer;
        if (author == null) {
            const a = packager.info.metadata.author;
            if (a == null || a.email == null) {
                errors.push(errorMessages.authorEmailIsMissed);
            }
            else {
                author = `${a.name} <${a.email}>`;
            }
        }
        if (errors.length > 0) {
            throw new Error(errors.join("\n\n"));
        }
        return {
            name: (_a = options.packageName) !== null && _a !== void 0 ? _a : this.packager.appInfo.linuxPackageName,
            maintainer: author,
            url: projectUrl,
            vendor: options.vendor || author,
        };
    }
    async build(appOutDir, arch) {
        var _a;
        const target = this.name;
        // tslint:disable:no-invalid-template-strings
        let nameFormat = "${name}-${version}-${arch}.${ext}";
        let isUseArchIfX64 = false;
        if (target === "deb") {
            nameFormat = "${name}_${version}_${arch}.${ext}";
            isUseArchIfX64 = true;
        }
        else if (target === "rpm") {
            nameFormat = "${name}-${version}.${arch}.${ext}";
            isUseArchIfX64 = true;
        }
        const packager = this.packager;
        const artifactPath = path.join(this.outDir, packager.expandArtifactNamePattern(this.options, target, arch, nameFormat, !isUseArchIfX64));
        await packager.info.callArtifactBuildStarted({
            targetPresentableName: target,
            file: artifactPath,
            arch,
        });
        await fs_1.unlinkIfExists(artifactPath);
        if (packager.packagerOptions.prepackaged != null) {
            await promises_1.mkdir(this.outDir, { recursive: true });
        }
        const scripts = await this.scriptFiles;
        const appInfo = packager.appInfo;
        const options = this.options;
        const synopsis = options.synopsis;
        const args = [
            "--architecture",
            builder_util_1.toLinuxArchString(arch, target),
            "--after-install",
            scripts[0],
            "--after-remove",
            scripts[1],
            "--description",
            appInfo_1.smarten(target === "rpm" ? this.helper.getDescription(options) : `${synopsis || ""}\n ${this.helper.getDescription(options)}`),
            "--version",
            appInfo.version,
            "--package",
            artifactPath,
        ];
        appBuilder_1.objectToArgs(args, (await this.computeFpmMetaInfoOptions()));
        const packageCategory = options.packageCategory;
        if (packageCategory != null) {
            args.push("--category", packageCategory);
        }
        if (target === "deb") {
            args.push("--deb-priority", (_a = options.priority) !== null && _a !== void 0 ? _a : "optional");
        }
        else if (target === "rpm") {
            if (synopsis != null) {
                args.push("--rpm-summary", appInfo_1.smarten(synopsis));
            }
        }
        const fpmConfiguration = {
            args,
            target,
        };
        if (options.compression != null) {
            fpmConfiguration.compression = options.compression;
        }
        // noinspection JSDeprecatedSymbols
        const depends = options.depends;
        if (depends != null) {
            if (Array.isArray(depends)) {
                fpmConfiguration.customDepends = depends;
            }
            else {
                // noinspection SuspiciousTypeOfGuard
                if (typeof depends === "string") {
                    fpmConfiguration.customDepends = [depends];
                }
                else {
                    throw new Error(`depends must be Array or String, but specified as: ${depends}`);
                }
            }
        }
        builder_util_1.use(packager.info.metadata.license, it => args.push("--license", it));
        builder_util_1.use(appInfo.buildNumber, it => args.push("--iteration", it));
        builder_util_1.use(options.fpm, it => args.push(...it));
        args.push(`${appOutDir}/=${LinuxTargetHelper_1.installPrefix}/${appInfo.sanitizedProductName}`);
        for (const icon of await this.helper.icons) {
            const extWithDot = path.extname(icon.file);
            const sizeName = extWithDot === ".svg" ? "scalable" : `${icon.size}x${icon.size}`;
            args.push(`${icon.file}=/usr/share/icons/hicolor/${sizeName}/apps/${packager.executableName}${extWithDot}`);
        }
        const mimeTypeFilePath = await this.helper.mimeTypeFiles;
        if (mimeTypeFilePath != null) {
            args.push(`${mimeTypeFilePath}=/usr/share/mime/packages/${packager.executableName}.xml`);
        }
        const desktopFilePath = await this.helper.writeDesktopEntry(this.options);
        args.push(`${desktopFilePath}=/usr/share/applications/${packager.executableName}.desktop`);
        if (packager.packagerOptions.effectiveOptionComputed != null && (await packager.packagerOptions.effectiveOptionComputed([args, desktopFilePath]))) {
            return;
        }
        const env = {
            ...process.env,
            SZA_PATH: _7zip_bin_1.path7za,
            SZA_COMPRESSION_LEVEL: packager.compression === "store" ? "0" : "9",
        };
        // rpmbuild wants directory rpm with some default config files. Even if we can use dylibbundler, path to such config files are not changed (we need to replace in the binary)
        // so, for now, brew install rpm is still required.
        if (target !== "rpm" && (await macosVersion_1.isMacOsSierra())) {
            const linuxToolsPath = await tools_1.getLinuxToolsPath();
            Object.assign(env, {
                PATH: bundledTool_1.computeEnv(process.env.PATH, [path.join(linuxToolsPath, "bin")]),
                DYLD_LIBRARY_PATH: bundledTool_1.computeEnv(process.env.DYLD_LIBRARY_PATH, [path.join(linuxToolsPath, "lib")]),
            });
        }
        await builder_util_1.executeAppBuilder(["fpm", "--configuration", JSON.stringify(fpmConfiguration)], undefined, { env });
        await packager.dispatchArtifactCreated(artifactPath, this, arch);
    }
}
exports.default = FpmTarget;
async function writeConfigFile(tmpDir, templatePath, options) {
    //noinspection JSUnusedLocalSymbols
    function replacer(match, p1) {
        if (p1 in options) {
            return options[p1];
        }
        else {
            throw new Error(`Macro ${p1} is not defined`);
        }
    }
    const config = (await promises_1.readFile(templatePath, "utf8")).replace(/\${([a-zA-Z]+)}/g, replacer).replace(/<%=([a-zA-Z]+)%>/g, (match, p1) => {
        builder_util_1.log.warn("<%= varName %> is deprecated, please use ${varName} instead");
        return replacer(match, p1.trim());
    });
    const outputPath = await tmpDir.getTempFile({ suffix: path.basename(templatePath, ".tpl") });
    await fs_extra_1.outputFile(outputPath, config);
    return outputPath;
}
//# sourceMappingURL=fpm.js.map