'use strict'; exports = module.exports = { addProfile, removeProfile }; const assert = require('assert'), BoxError = require('./boxerror.js'), debug = require('debug')('collectd'), fs = require('fs'), path = require('path'), paths = require('./paths.js'), safe = require('safetydance'), shell = require('./shell.js'); const CONFIGURE_COLLECTD_CMD = path.join(__dirname, 'scripts/configurecollectd.sh'); function addProfile(name, profile, callback) { assert.strictEqual(typeof name, 'string'); assert.strictEqual(typeof profile, 'string'); assert.strictEqual(typeof callback, 'function'); const configFilePath = path.join(paths.COLLECTD_APPCONFIG_DIR, `${name}.conf`); // skip restarting collectd if the profile already exists with the same contents const currentProfile = safe.fs.readFileSync(configFilePath, 'utf8') || ''; if (currentProfile === profile) return callback(null); fs.writeFile(configFilePath, profile, function (error) { if (error) return callback(new BoxError(BoxError.FS_ERROR, `Error writing collectd config: ${error.message}`)); shell.sudo('addCollectdProfile', [ CONFIGURE_COLLECTD_CMD, 'add', name ], {}, function (error) { if (error) return callback(new BoxError(BoxError.COLLECTD_ERROR, 'Could not add collectd config')); callback(null); }); }); } function removeProfile(name, callback) { assert.strictEqual(typeof name, 'string'); assert.strictEqual(typeof callback, 'function'); fs.unlink(path.join(paths.COLLECTD_APPCONFIG_DIR, `${name}.conf`), function (error) { if (error && error.code !== 'ENOENT') debug('Error removing collectd profile', error); shell.sudo('removeCollectdProfile', [ CONFIGURE_COLLECTD_CMD, 'remove', name ], {}, function (error) { if (error) return callback(new BoxError(BoxError.COLLECTD_ERROR, 'Could not remove collectd config')); callback(null); }); }); }