function getInstallCommand() {

    if (process.argv.length > 2) {
        const command = process.argv[2].toLowerCase();
        if ((command === 'install') || (command === 'uninstall')) {
            return command;
        }
    }
}

module.exports = {

    installMode: function (serviceInfo) {

        const installCommand = getInstallCommand();
        if (!installCommand) {
            return false;
        }

        process.on('uncaughtException', function (err) {

            const expectedUninstallError =
                (err.message.indexOf('EPERM') === 0) &&
                (err.message.indexOf(serviceInfo.name.toLowerCase() + '.exe') > -1);

            if (expectedUninstallError) {
                console.log('Windows service uninstalled successfully');
            } else {
                console.log(err.message);
            }
        });

        const Service = require('node-windows').Service;
        const svc = new Service(serviceInfo);

        svc.on('install', function () {
            console.log('Windows service installed successfully, now starting...');
            setTimeout(function () {
                svc.start();
            }, 5000);
        });

        svc.on('start', function () {
            console.log('%s service started', svc.name)
        });

        svc.on('stop', function () {
            console.log('%s service stopped...', svc.name);
        });

        svc.on('alreadystopped', function () {
            console.log('%s service is already stopped...', svc.name);
        });

        svc.on('uninstall', function () {
            console.log('Windows service uninstalled successfully');
        });

        if (installCommand === 'install') {
            console.log('Installing %s Windows service...', svc.name);
            svc.install();
        } else {
            console.log('Uninstalling %s Windows service...', svc.name);
            svc.uninstall(5);
        }

        return true;
    }
};
