"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
exports.installFirmwareCommand = void 0;
const rxjs_1 = require("rxjs");
const url_1 = __importDefault(require("url"));
const hw_transport_1 = require("@ledgerhq/hw-transport");
const package_json_1 = require("../../../../package.json");
const live_env_1 = require("@ledgerhq/live-env");
const logs_1 = require("@ledgerhq/logs");
const socket_1 = require("../../../socket");
const operators_1 = require("rxjs/operators");
const errors_1 = require("@ledgerhq/errors");
const core_1 = require("../core");
/**
 * Creates a scriptrunner connection with the /install API endpoint of the HSM in order to install (upload)
 * an OSU (operating system updater).
 * This is the same endpoint that is used to install applications, however the parameters that are
 * passed are different. Besides that, the emitted events are semantically different. This is why
 * this is a dedicated command to OSU installations.
 *
 * @param transport The transport object to contact the device
 * @param param1 The firmware details to be installed
 * @returns An observable that emits the events according to the progression of the firmware installation
 */
function installFirmwareCommand(transport, { targetId, firmware }) {
    const tracer = new logs_1.LocalTracer(core_1.LOG_TYPE, { function: "installFirmwareCommand" });
    tracer.trace("Starting", {
        targetId,
        osuFirmware: firmware,
    });
    return (0, socket_1.createDeviceSocket)(transport, {
        url: url_1.default.format({
            pathname: `${(0, live_env_1.getEnv)("BASE_SOCKET_URL")}/install`,
            query: {
                targetId,
                livecommonversion: package_json_1.version,
                perso: firmware.perso,
                firmware: firmware.firmware,
                firmwareKey: firmware.firmware_key,
            },
        }),
        unresponsiveExpectedDuringBulk: true,
        context: tracer.getContext(),
    }).pipe((0, operators_1.catchError)(error => {
        tracer.trace("Socket firmware error", { error });
        return remapSocketFirmwareError(error);
    }), (0, operators_1.filter)((e) => {
        return e.type === "bulk-progress" || e.type === "device-permission-requested";
    }), (0, operators_1.map)(e => {
        if (e.type === "bulk-progress") {
            return e.index === e.total - 1
                ? {
                    // the penultimate APDU of the bulk part of the installation is a blocking apdu and
                    // requires user validation
                    type: "firmwareInstallPermissionRequested",
                }
                : e.index === e.total
                    ? {
                        // the last APDU of the bulk part of the instalation means that the user validated
                        // the installation of the OSU firmware
                        type: "firmwareInstallPermissionGranted",
                    }
                    : {
                        type: "progress",
                        progress: e.progress,
                    };
        }
        // then type is "device-permission-requested"
        return { type: "allowSecureChannelRequested" };
    }), (0, operators_1.catchError)(error => {
        tracer.trace("Socket unresponsive error", { error });
        return remapSocketUnresponsiveError(error);
    }));
}
exports.installFirmwareCommand = installFirmwareCommand;
const remapSocketUnresponsiveError = (e) => {
    if (e instanceof errors_1.ManagerDeviceLockedError) {
        return (0, rxjs_1.of)({ type: "unresponsive" });
    }
    return (0, rxjs_1.throwError)(e);
};
const remapSocketFirmwareError = (e) => {
    if (!e || !e.message)
        return (0, rxjs_1.throwError)(() => e);
    if (e.message.startsWith("invalid literal")) {
        // hack to detect the case you're not in good condition (not in dashboard)
        return (0, rxjs_1.throwError)(() => new errors_1.DeviceOnDashboardExpected());
    }
    const status = e instanceof hw_transport_1.TransportStatusError
        ? e.statusCode.toString(16)
        : e.message.slice(e.message.length - 4);
    switch (status) {
        case "6a84":
        case "5103":
            return (0, rxjs_1.throwError)(() => new errors_1.ManagerFirmwareNotEnoughSpaceError());
        case "6a85":
        case "5102":
            return (0, rxjs_1.throwError)(() => new errors_1.UserRefusedFirmwareUpdate());
        case "6985":
        case "5501":
            return (0, rxjs_1.throwError)(() => new errors_1.UserRefusedFirmwareUpdate());
        default:
            return (0, rxjs_1.throwError)(() => e);
    }
};
//# sourceMappingURL=installFirmware.js.map