"use strict";
var __decorate = (this && this.__decorate) || function (decorators, target, key, desc) {
    var c = arguments.length, r = c < 3 ? target : desc === null ? desc = Object.getOwnPropertyDescriptor(target, key) : desc, d;
    if (typeof Reflect === "object" && typeof Reflect.decorate === "function") r = Reflect.decorate(decorators, target, key, desc);
    else for (var i = decorators.length - 1; i >= 0; i--) if (d = decorators[i]) r = (c < 3 ? d(r) : c > 3 ? d(target, key, r) : d(target, key)) || r;
    return c > 3 && r && Object.defineProperty(target, key, r), r;
};
var __metadata = (this && this.__metadata) || function (k, v) {
    if (typeof Reflect === "object" && typeof Reflect.metadata === "function") return Reflect.metadata(k, v);
};
Object.defineProperty(exports, "__esModule", { value: true });
const common_1 = require("@nestjs/common");
const os = require("os");
const path = require("path");
const fs = require("fs-extra");
const crypto = require("crypto");
const semver = require("semver");
let ConfigService = class ConfigService {
    constructor() {
        this.name = 'homebridge-config-ui-x';
        this.configPath = process.env.UIX_CONFIG_PATH || path.resolve(os.homedir(), '.homebridge/config.json');
        this.storagePath = process.env.UIX_STORAGE_PATH || path.resolve(os.homedir(), '.homebridge');
        this.customPluginPath = process.env.UIX_CUSTOM_PLUGIN_PATH;
        this.secretPath = path.resolve(this.storagePath, '.uix-secrets');
        this.authPath = path.resolve(this.storagePath, 'auth.json');
        this.accessoryLayoutPath = path.resolve(this.storagePath, 'accessories', 'uiAccessoriesLayout.json');
        this.homebridgeInsecureMode = Boolean(process.env.UIX_INSECURE_MODE === '1');
        this.homebridgeNoTimestamps = Boolean(process.env.UIX_LOG_NO_TIMESTAMPS === '1');
        this.minimumNodeVersion = '8.15.1';
        this.serviceMode = (process.env.UIX_SERVICE_MODE === '1');
        this.runningInDocker = Boolean(process.env.HOMEBRIDGE_CONFIG_UI === '1');
        this.runningInLinux = (!this.runningInDocker && os.platform() === 'linux');
        this.ableToConfigureSelf = (!this.runningInDocker || semver.satisfies(process.env.CONFIG_UI_VERSION, '>=3.5.5'), { includePrerelease: true });
        this.enableTerminalAccess = this.runningInDocker || Boolean(process.env.HOMEBRIDGE_CONFIG_UI_TERMINAL === '1');
        this.branding = process.env.CONFIG_UI_BRANDING || false;
        this.startupScript = path.resolve(this.storagePath, 'startup.sh');
        this.dockerEnvFile = path.resolve(this.storagePath, '.docker.env');
        this.package = fs.readJsonSync(path.resolve(process.env.UIX_BASE_PATH, 'package.json'));
        this.homebridgeConfig = fs.readJSONSync(this.configPath);
        this.ui = Array.isArray(this.homebridgeConfig.platforms) ? this.homebridgeConfig.platforms.find(x => x.platform === 'config') : undefined;
        if (!this.ui) {
            this.ui = {
                name: 'Config',
            };
        }
        process.env.UIX_PLUGIN_NAME = this.ui.name || 'homebridge-config-ui-x';
        if (this.runningInDocker) {
            this.setConfigForDocker();
        }
        if (this.serviceMode) {
            this.setConfigForServiceMode();
        }
        if (!this.ui.port) {
            this.ui.port = 8080;
        }
        if (!this.ui.sessionTimeout) {
            this.ui.sessionTimeout = 28800;
        }
        this.secrets = this.getSecrets();
        this.instanceId = this.getInstanceId();
    }
    uiSettings() {
        return {
            env: {
                ableToConfigureSelf: this.ableToConfigureSelf,
                enableAccessories: this.homebridgeInsecureMode,
                enableTerminalAccess: this.enableTerminalAccess,
                homebridgeInstanceName: this.homebridgeConfig.bridge.name,
                nodeVersion: process.version,
                packageName: this.package.name,
                packageVersion: this.package.version,
                runningInDocker: this.runningInDocker,
                runningInLinux: this.runningInLinux,
                temperatureUnits: this.ui.tempUnits || 'c',
                websocketCompatibilityMode: this.ui.websocketCompatibilityMode || false,
                branding: this.branding,
                instanceId: this.instanceId,
            },
            formAuth: Boolean(this.ui.auth !== 'none'),
            theme: this.ui.theme || 'teal',
            serverTimestamp: new Date().toISOString(),
        };
    }
    setConfigForDocker() {
        this.ui.restart = 'killall -9 homebridge && killall -9 homebridge-config-ui-x';
        this.homebridgeInsecureMode = Boolean(process.env.HOMEBRIDGE_INSECURE === '1');
        this.ui.sudo = false;
        this.ui.log = {
            method: 'file',
            path: '/homebridge/logs/homebridge.log',
        };
        if (!this.ui.port && process.env.HOMEBRIDGE_CONFIG_UI_PORT) {
            this.ui.port = parseInt(process.env.HOMEBRIDGE_CONFIG_UI_PORT, 10);
        }
        this.ui.theme = this.ui.theme || process.env.HOMEBRIDGE_CONFIG_UI_THEME || 'teal';
        this.ui.auth = this.ui.auth || process.env.HOMEBRIDGE_CONFIG_UI_AUTH || 'form';
        this.ui.temp = this.ui.temp || process.env.HOMEBRIDGE_CONFIG_UI_TEMP || undefined;
        this.ui.loginWallpaper = this.ui.loginWallpaper || process.env.HOMEBRIDGE_CONFIG_UI_LOGIN_WALLPAPER || undefined;
    }
    setConfigForServiceMode() {
        this.ui.restart = undefined;
        this.homebridgeInsecureMode = true;
        this.ui.log = {
            method: 'file',
            path: path.resolve(this.storagePath, 'homebridge.log'),
        };
    }
    getSecrets() {
        if (fs.pathExistsSync(this.secretPath)) {
            try {
                const secrets = fs.readJsonSync(this.secretPath);
                if (!secrets.secretKey) {
                    return this.generateSecretToken();
                }
                else {
                    return secrets;
                }
            }
            catch (e) {
                return this.generateSecretToken();
            }
        }
        else {
            return this.generateSecretToken();
        }
    }
    generateSecretToken() {
        const secrets = {
            secretKey: crypto.randomBytes(32).toString('hex'),
        };
        fs.writeJsonSync(this.secretPath, secrets);
        return secrets;
    }
    getInstanceId() {
        return crypto.createHash('sha256').update(this.secrets.secretKey).digest('hex');
    }
};
ConfigService = __decorate([
    common_1.Injectable(),
    __metadata("design:paramtypes", [])
], ConfigService);
exports.ConfigService = ConfigService;
//# sourceMappingURL=config.service.js.map