"use strict";

Object.defineProperty(exports, "__esModule", {
    value: true
});
exports.AppImageUpdater = undefined;

var _bluebirdLst;

function _load_bluebirdLst() {
    return _bluebirdLst = require("bluebird-lst");
}

var _bluebirdLst2;

function _load_bluebirdLst2() {
    return _bluebirdLst2 = _interopRequireDefault(require("bluebird-lst"));
}

var _child_process;

function _load_child_process() {
    return _child_process = require("child_process");
}

require("source-map-support/register");

var _differentialPackage;

function _load_differentialPackage() {
    return _differentialPackage = require("./differentialPackage");
}

var _main;

function _load_main() {
    return _main = require("./main");
}

var _BaseUpdater;

function _load_BaseUpdater() {
    return _BaseUpdater = require("./BaseUpdater");
}

var _blockMapApi;

function _load_blockMapApi() {
    return _blockMapApi = require("builder-util-runtime/out/blockMapApi");
}

var _jsYaml;

function _load_jsYaml() {
    return _jsYaml = require("js-yaml");
}

var _fsExtraP;

function _load_fsExtraP() {
    return _fsExtraP = require("fs-extra-p");
}

var _path = _interopRequireWildcard(require("path"));

var _electronIsDev;

function _load_electronIsDev() {
    return _electronIsDev = _interopRequireDefault(require("electron-is-dev"));
}

var _Provider;

function _load_Provider() {
    return _Provider = require("./Provider");
}

function _interopRequireWildcard(obj) { if (obj && obj.__esModule) { return obj; } else { var newObj = {}; if (obj != null) { for (var key in obj) { if (Object.prototype.hasOwnProperty.call(obj, key)) newObj[key] = obj[key]; } } newObj.default = obj; return newObj; } }

function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; }

class AppImageUpdater extends (_BaseUpdater || _load_BaseUpdater()).BaseUpdater {
    constructor(options, app) {
        super(options, app);
    }
    checkForUpdatesAndNotify() {
        if ((_electronIsDev || _load_electronIsDev()).default) {
            return (_bluebirdLst2 || _load_bluebirdLst2()).default.resolve(null);
        }
        if (process.env.APPIMAGE == null) {
            this._logger.warn("APPIMAGE env is not defined, current application is not an AppImage");
            return (_bluebirdLst2 || _load_bluebirdLst2()).default.resolve(null);
        }
        return super.checkForUpdatesAndNotify();
    }
    /*** @private */
    doDownloadUpdate(updateInfo, cancellationToken) {
        var _this = this;

        return (0, (_bluebirdLst || _load_bluebirdLst()).coroutine)(function* () {
            const fileInfo = (0, (_Provider || _load_Provider()).findFile)((yield _this.provider).resolveFiles(updateInfo), "AppImage");
            const requestHeaders = yield _this.computeRequestHeaders();
            const downloadOptions = {
                skipDirCreation: true,
                headers: requestHeaders,
                cancellationToken,
                sha512: fileInfo.info.sha512
            };
            let installerPath = _this.downloadedUpdateHelper.getDownloadedFile(updateInfo, fileInfo);
            if (installerPath != null) {
                return [installerPath];
            }
            yield _this.executeDownload(downloadOptions, fileInfo, (() => {
                var _ref = (0, (_bluebirdLst || _load_bluebirdLst()).coroutine)(function* (tempDir, destinationFile) {
                    installerPath = destinationFile;
                    const oldFile = process.env.APPIMAGE;
                    if (oldFile == null) {
                        throw new Error("APPIMAGE env is not defined");
                    }
                    let isDownloadFull = false;
                    try {
                        yield new (_differentialPackage || _load_differentialPackage()).DifferentialDownloader(fileInfo.info, _this.httpExecutor, {
                            newUrl: fileInfo.url.href,
                            oldPackageFile: oldFile,
                            logger: _this._logger,
                            newFile: installerPath,
                            requestHeaders
                        }).downloadAppImage((0, (_jsYaml || _load_jsYaml()).safeLoad)((yield (0, (_blockMapApi || _load_blockMapApi()).readBlockMapDataFromAppImage)(oldFile))));
                    } catch (e) {
                        _this._logger.error(`Cannot download differentially, fallback to full download: ${e.stack || e}`);
                        // during test (developer machine mac) we must throw error
                        isDownloadFull = process.platform === "linux";
                    }
                    if (isDownloadFull) {
                        yield _this.httpExecutor.download(fileInfo.url.href, installerPath, downloadOptions);
                    }
                });

                return function (_x, _x2) {
                    return _ref.apply(this, arguments);
                };
            })());
            _this.downloadedUpdateHelper.setDownloadedFile(installerPath, null, updateInfo, fileInfo);
            _this.addQuitHandler();
            _this.emit((_main || _load_main()).UPDATE_DOWNLOADED, _this.updateInfo);
            return [installerPath];
        })();
    }
    doInstall(installerPath, isSilent, isForceRunAfter) {
        const args = [""];
        if (isForceRunAfter) {
            args.push("--force-run");
        }
        const appImageFile = process.env.APPIMAGE;
        if (appImageFile == null) {
            throw new Error("APPIMAGE env is not defined");
        }
        const spawnOptions = {
            detached: true,
            stdio: "ignore",
            env: {
                APPIMAGE_SILENT_INSTALL: "true"
            }
        };
        if (!isForceRunAfter) {
            spawnOptions.env.APPIMAGE_EXIT_AFTER_INSTALL = "true";
        }
        let destination;
        if (_path.basename(installerPath) === _path.basename(appImageFile)) {
            // no version in the file name, overwrite existing
            destination = appImageFile;
        } else {
            destination = _path.join(_path.dirname(appImageFile), _path.basename(installerPath));
            spawnOptions.env.APPIMAGE_DELETE_OLD_FILE = appImageFile;
        }
        (0, (_fsExtraP || _load_fsExtraP()).move)(installerPath, destination, { overwrite: true }).then(() => (0, (_fsExtraP || _load_fsExtraP()).chmod)(destination, "0755")).then(() => {
            try {
                (0, (_child_process || _load_child_process()).spawn)(installerPath, args, spawnOptions).unref();
            } catch (e) {
                this.dispatchError(e);
            }
        }).catch(e => this.dispatchError(e));
        return true;
    }
}
exports.AppImageUpdater = AppImageUpdater; //# sourceMappingURL=AppImageUpdater.js.map