"use strict";
Object.defineProperty(exports, "__esModule", { value: true });
exports.GetNetworkService = void 0;
const child_process_1 = require("child_process");
const os = require("os");
const LogTypes_1 = require("../../common/LogTypes");
let nwServiceSingleton = null;
function GetNetworkService(logger) {
    if (nwServiceSingleton === null) {
        nwServiceSingleton = (os.platform() === 'linux') ? new RpiNetworkService(logger) : new EmulatorNetworkService();
    }
    return nwServiceSingleton;
}
exports.GetNetworkService = GetNetworkService;
class EmulatorNetworkService {
    constructor() {
        this.config = {
            ip: this.GetIpAddress(),
            netmask: 24,
            gateway: '192.168.0.1',
            nameserver: ''
        };
    }
    GetIpAddress() {
        return '192.168.0.100';
    }
    GetConfiguration() {
        return this.config;
    }
    UpdateConfiguration(config) {
        Object.assign(this.config, config);
    }
    GetDateTime() {
        return '';
    }
    SetDateTime(value) {
        console.log(value);
    }
    EnableWireguard(_enabled) {
    }
    GetWireguardEnabledAsync() {
        return Promise.resolve(false);
    }
    GetWireguardStatusAsync() {
        return Promise.resolve(false);
    }
}
class RpiNetworkService {
    constructor(logger) {
        this.config = {
            ip: '',
            netmask: 0,
            gateway: '',
            nameserver: ''
        };
        this.logger = logger;
        this.readNetworkSettings();
    }
    readNetworkSettings() {
        (0, child_process_1.exec)('nmcli --terse connection show eth0', { encoding: 'utf-8' }, (err, data) => {
            if (err) {
                console.log(err);
            }
            else {
                const ip_match = /^ipv4\.addresses\:([\d\.]+)\/(\d+)\s*$/gm.exec(data);
                const gw_match = /^ipv4\.gateway\:([\d\.]+)\s*$/gm.exec(data);
                const ns_match = /^ipv4\.dns\:([\d\.]+)\s*$/gm.exec(data);
                this.config.ip = (ip_match) ? ip_match[1] : '';
                this.config.netmask = (ip_match) ? parseInt(ip_match[2], 10) : 0;
                this.config.gateway = (gw_match) ? gw_match[1] : '';
                this.config.nameserver = (ns_match) ? ns_match[1] : '';
                console.log(this.config);
            }
        });
    }
    GetIpAddress() {
        const eth0 = os.networkInterfaces()['eth0'];
        if (eth0) {
            return eth0[0]['cidr'] || eth0[0]['address'] || '';
        }
        return '';
    }
    GetConfiguration() {
        return this.config;
    }
    UpdateConfiguration(config) {
        if (!config)
            return;
        if (!config.ip || config.ip === "" || !/^(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$/.test(config.ip))
            return;
        if (!config.netmask || config.netmask < 1 || config.netmask > 31 || parseInt("" + config.netmask, 10) != config.netmask)
            return;
        if (!config.gateway || !/^$|^(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$/.test(config.gateway))
            return;
        if (!config.nameserver || !/^$|^(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\.(25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)$/.test(config.nameserver))
            return;
        Object.assign(this.config, config);
        (0, child_process_1.exec)(`sudo nmcli connection modify eth0 ipv4.method manual ipv4.addr "${config.ip}/${config.netmask}"`, { encoding: 'utf-8' }, (err, _data) => {
            if (err) {
                console.log(err);
            }
            this.readNetworkSettings();
        });
        (0, child_process_1.exec)(`sudo nmcli connection modify eth0 ipv4.gateway "${config.gateway}"`, { encoding: 'utf-8' }, (err, _data) => {
            if (err) {
                console.log(err);
            }
            this.readNetworkSettings();
        });
        (0, child_process_1.exec)(`sudo nmcli connection modify eth0 ipv4.dns "${config.nameserver}"`, { encoding: 'utf-8' }, (err, _data) => {
            if (err) {
                console.log(err);
            }
            this.readNetworkSettings();
        });
    }
    GetDateTime() {
        try {
            const data = (0, child_process_1.execSync)('date', { encoding: 'utf-8' });
            return data;
        }
        catch (e) {
            console.log(e);
            return 'error';
        }
    }
    SetDateTime(value) {
        try {
            const d = new Date(value);
            const execString = `date -s "${d.getFullYear()}-${d.getMonth() + 1}-${d.getDate()} ${d.getHours()}:${d.getMinutes()}:${d.getSeconds()}"`;
            const t = (0, child_process_1.execSync)(execString, { encoding: 'utf-8' });
            this.logger.log(`Set date/time: "${t}"`, LogTypes_1.LogLevel.Info, { type: 'SYSTEM', id: '' });
        }
        catch (e) {
            this.logger.log(`Error setting date/time: "${e}"`, LogTypes_1.LogLevel.Error, { type: 'SYSTEM', id: '' });
        }
    }
    EnableWireguard(enabled) {
        if (enabled) {
            (0, child_process_1.exec)('sudo nmcli connection up wg0 && sudo nmcli connection modify wg0 autoconnect yes', (err, _data) => {
                if (err)
                    console.log(err);
            });
        }
        else {
            (0, child_process_1.exec)('sudo nmcli connection down wg0 && sudo nmcli connection modify wg0 autoconnect no', (err, _data) => {
                if (err)
                    console.log(err);
            });
        }
    }
    GetWireguardEnabledAsync() {
        return new Promise((resolve, _) => {
            (0, child_process_1.exec)('sudo nmcli -f GENERAL.STATE -t device show wg0', { encoding: 'utf-8' }, (err, data) => {
                if (err) {
                    console.log(err);
                    resolve(false);
                    return;
                }
                const fields = data.split(':');
                if (fields.length > 1) {
                    resolve(!fields[1].startsWith('30'));
                    return;
                }
                resolve(false);
            });
        });
    }
    GetWireguardStatusAsync() {
        return new Promise((resolve, _) => {
            (0, child_process_1.exec)('ping -q -c 3 -I wg0 10.198.79.1 > /dev/null', { encoding: 'utf-8' }, (err, _) => {
                if (err) {
                    console.log(err);
                    resolve(false);
                    return;
                }
                resolve(true);
            });
        });
    }
}
//# sourceMappingURL=NetworkService.js.map