"use strict";
var __createBinding = (this && this.__createBinding) || (Object.create ? (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    var desc = Object.getOwnPropertyDescriptor(m, k);
    if (!desc || ("get" in desc ? !m.__esModule : desc.writable || desc.configurable)) {
      desc = { enumerable: true, get: function() { return m[k]; } };
    }
    Object.defineProperty(o, k2, desc);
}) : (function(o, m, k, k2) {
    if (k2 === undefined) k2 = k;
    o[k2] = m[k];
}));
var __setModuleDefault = (this && this.__setModuleDefault) || (Object.create ? (function(o, v) {
    Object.defineProperty(o, "default", { enumerable: true, value: v });
}) : function(o, v) {
    o["default"] = v;
});
var __importStar = (this && this.__importStar) || function (mod) {
    if (mod && mod.__esModule) return mod;
    var result = {};
    if (mod != null) for (var k in mod) if (k !== "default" && Object.prototype.hasOwnProperty.call(mod, k)) __createBinding(result, mod, k);
    __setModuleDefault(result, mod);
    return result;
};
var __awaiter = (this && this.__awaiter) || function (thisArg, _arguments, P, generator) {
    function adopt(value) { return value instanceof P ? value : new P(function (resolve) { resolve(value); }); }
    return new (P || (P = Promise))(function (resolve, reject) {
        function fulfilled(value) { try { step(generator.next(value)); } catch (e) { reject(e); } }
        function rejected(value) { try { step(generator["throw"](value)); } catch (e) { reject(e); } }
        function step(result) { result.done ? resolve(result.value) : adopt(result.value).then(fulfilled, rejected); }
        step((generator = generator.apply(thisArg, _arguments || [])).next());
    });
};
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.handleSquirrelArgs = exports.installUpdate = void 0;
const fs_extra_1 = __importDefault(require("fs-extra"));
const childProcess = __importStar(require("child_process"));
const path = __importStar(require("path"));
const commons_1 = require("@wireapp/commons");
const shortcuts_1 = require("./shortcuts");
const getLogger_1 = require("../logging/getLogger");
const EnvironmentUtil = __importStar(require("../runtime/EnvironmentUtil"));
const lifecycle = __importStar(require("../runtime/lifecycle"));
const config_1 = require("../settings/config");
const logger = (0, getLogger_1.getLogger)(path.basename(__filename));
const appFolder = path.resolve(process.execPath, '..');
const rootFolder = path.resolve(appFolder, '..');
const updateDotExe = path.join(rootFolder, 'Update.exe');
const exeName = path.basename(process.execPath);
const exePath = path.join(rootFolder, exeName);
const windowsAppData = process.env.APPDATA;
if (!windowsAppData && EnvironmentUtil.platform.IS_WINDOWS) {
    logger.error('No Windows AppData directory found.');
}
var SQUIRREL_EVENT;
(function (SQUIRREL_EVENT) {
    SQUIRREL_EVENT["INSTALL"] = "--squirrel-install";
    SQUIRREL_EVENT["OBSOLETE"] = "--squirrel-obsolete";
    SQUIRREL_EVENT["UNINSTALL"] = "--squirrel-uninstall";
    SQUIRREL_EVENT["UPDATED"] = "--squirrel-updated";
})(SQUIRREL_EVENT || (SQUIRREL_EVENT = {}));
function spawn(command, args) {
    const commandFile = path.basename(command);
    return new Promise(resolve => {
        const spawnedProcess = childProcess
            .spawn(command, args)
            .on('error', error => logger.error(error))
            .on('close', (code, signal) => {
            if (code !== 0) {
                const exitReason = signal || `exit code ${code}`;
                logger.error(`Running command "${command}" failed: received ${exitReason}`);
            }
            resolve();
        });
        if (spawnedProcess.stdout) {
            spawnedProcess.stdout.on('data', (data) => {
                const stringifiedData = data.toString().trim();
                if (stringifiedData) {
                    logger.info(`${commandFile}: ${stringifiedData}`);
                }
            });
        }
        if (spawnedProcess.stderr) {
            spawnedProcess.stderr.on('data', (data) => {
                const stringifiedData = data.toString().trim();
                if (stringifiedData) {
                    logger.error(`${commandFile}: ${stringifiedData}`);
                }
            });
        }
    });
}
function spawnUpdate(args) {
    return __awaiter(this, void 0, void 0, function* () {
        logger.info(`Running updater with args ${JSON.stringify(args)} ...`);
        const updateDotExeExists = fs_extra_1.default.existsSync(updateDotExe);
        if (!updateDotExeExists) {
            logger.info(`Could not find updater in "${updateDotExe}".`);
        }
        try {
            yield spawn(updateDotExe, args);
        }
        catch (error) {
            logger.error(error);
        }
    });
}
function installUpdate() {
    return __awaiter(this, void 0, void 0, function* () {
        logger.info(`Checking for Windows updates at "${EnvironmentUtil.app.UPDATE_URL_WIN}" ...`);
        yield spawnUpdate(['--update', EnvironmentUtil.app.UPDATE_URL_WIN]);
    });
}
exports.installUpdate = installUpdate;
function scheduleUpdate() {
    return __awaiter(this, void 0, void 0, function* () {
        const squirrelDelay = config_1.config.squirrelUpdateInterval.DELAY;
        const squirrelInterval = config_1.config.squirrelUpdateInterval.INTERVAL;
        const nextCheck = squirrelDelay / config_1.MINUTE_IN_MILLIS;
        const regularCheck = squirrelInterval / config_1.HOUR_IN_MILLIS;
        const readableNextCheck = `${nextCheck} ${commons_1.StringUtil.pluralize('minute', nextCheck)}`;
        const readableRegularCheck = `${regularCheck} ${commons_1.StringUtil.pluralize('hour', regularCheck)}`;
        logger.info(`Scheduling Windows update to check in "${readableNextCheck}" and every "${readableRegularCheck}" ...`);
        setTimeout(installUpdate, squirrelDelay);
        setInterval(installUpdate, squirrelInterval);
    });
}
function handleSquirrelArgs() {
    return __awaiter(this, void 0, void 0, function* () {
        const squirrelEvent = process.argv[1];
        switch (squirrelEvent) {
            case SQUIRREL_EVENT.INSTALL:
            case SQUIRREL_EVENT.UPDATED: {
                logger.info(`Creating shortcuts for exe ${exePath}...`);
                yield (0, shortcuts_1.createShortcuts)(exePath);
                yield lifecycle.quit();
                return;
            }
            case SQUIRREL_EVENT.UNINSTALL: {
                yield (0, shortcuts_1.removeShortcuts)();
                yield lifecycle.quit();
                return;
            }
            case SQUIRREL_EVENT.OBSOLETE: {
                yield lifecycle.quit();
                return;
            }
        }
        yield scheduleUpdate();
    });
}
exports.handleSquirrelArgs = handleSquirrelArgs;
//# sourceMappingURL=squirrel.js.map