"use strict";
var __importDefault = (this && this.__importDefault) || function (mod) {
    return (mod && mod.__esModule) ? mod : { "default": mod };
};
Object.defineProperty(exports, "__esModule", { value: true });
const node_child_process_1 = require("node:child_process");
const node_os_1 = require("node:os");
const node_path_1 = require("node:path");
const node_process_1 = __importDefault(require("node:process"));
const logger_service_1 = require("./core/logger/logger.service");
const logger = new logger_service_1.Logger();
function tryRebuildNodePtyModule() {
    const modulePath = (0, node_path_1.dirname)((0, node_path_1.dirname)(require.resolve('@homebridge/node-pty-prebuilt-multiarch')));
    logger.warn('[node-pty] Trying to rebuild automatically...');
    logger.warn(`[node-pty] Path: ${modulePath}.`);
    try {
        (0, node_child_process_1.execSync)('npm run install --unsafe-perm', {
            cwd: modulePath,
            stdio: 'ignore',
        });
    }
    catch (e) {
        if ((0, node_os_1.platform)() !== 'win32') {
            (0, node_child_process_1.execSync)('sudo -E -n run install --unsafe-perm', {
                cwd: modulePath,
                stdio: 'ignore',
            });
        }
        else {
            throw e;
        }
    }
}
function main() {
    try {
        require('@homebridge/node-pty-prebuilt-multiarch');
    }
    catch (e) {
        logger.error(e);
        logger.error(`[node-pty] Node.js ${node_process_1.default.version}.`);
        logger.error('[node-pty] Failed to load node-pty module.');
        logger.error('[node-pty] This could be because the installation of this plugin did not complete successfully '
            + 'or you may have recently upgraded Node.js to a new major version.');
        logger.error('[node-pty] Follow the steps below to resolve this issue.');
        try {
            tryRebuildNodePtyModule();
            logger.warn('[node-pty] Module rebuilt successfully (maybe) - if you are still encountering errors follow the steps below.');
        }
        catch (rebuildError) {
            logger.error('[node-pty] Failed to rebuild npm modules automatically. Manual operation is now required.');
        }
        const modulePath = (0, node_path_1.dirname)(__dirname);
        if ((node_process_1.default.env.UIX_SERVICE_MODE === '1')) {
            if ((0, node_os_1.platform)() === 'win32') {
                logger.warn('[node-pty] From the Node.js command prompt (run as Administrator) run this command to rebuild npm modules:\n');
                logger.warn('hb-service rebuild\n');
            }
            else {
                logger.warn('[node-pty] From the terminal run this command to rebuild npm modules:\n');
                logger.warn('sudo hb-service rebuild\n');
            }
            throw new Error('Node.js global modules rebuild required. See log errors above.');
        }
        else {
            if ((0, node_os_1.platform)() === 'win32') {
                logger.warn('[node-pty] From the Node.js command prompt (run as Administrator) run these commands (exact commands may vary):\n');
                logger.warn('npm uninstall -g homebridge-config-ui-x');
                logger.warn('npm install -g homebridge-config-ui-x\n');
            }
            else if ((0, node_os_1.platform)() === 'darwin') {
                logger.warn('[node-pty] From the terminal run these commands (exact commands may vary):\n');
                logger.warn(`cd ${modulePath}`);
                logger.warn('sudo npm rebuild --unsafe-perm\n');
            }
            else {
                logger.warn('[node-pty] From the terminal run these commands (exact commands may vary):\n');
                logger.warn(`cd ${modulePath}`);
                logger.warn('sudo npm rebuild --unsafe-perm\n');
            }
        }
        node_process_1.default.exit(1);
    }
}
main();
node_process_1.default.on('unhandledRejection', (err) => {
    logger.error(err.toString());
    if (err.code === 'EADDRINUSE') {
        logger.error(`Another process or service on this host is using port ${err.port}.`);
        logger.error('Please stop the other service or change the port you have assigned to Homebridge UI.');
        logger.error('Ending process now.');
        setTimeout(() => node_process_1.default.exit(0));
    }
    else if (err.code === 'EACCES') {
        logger.error(`The process owner does not have permission to run services on port ${err.port}.`);
        logger.error('Please change the Homebridge UI port to something above 1024.');
        logger.error('Ending process now.');
        setTimeout(() => node_process_1.default.exit(0));
    }
    else {
        logger.error('Caught unhandled rejection error - details below:');
        console.error(err);
    }
});
//# sourceMappingURL=self-check.js.map