/**
Copyright: 2024 Contrast Security, Inc
  Contact: support@contrastsecurity.com
  License: Commercial

  NOTICE: This Software and the patented inventions embodied within may only be
  used as part of Contrast Security’s commercial offerings. Even though it is
  made available through public repositories, use of this Software is subject to
  the applicable End User Licensing Agreement found at
  https://www.contrastsecurity.com/enduser-terms-0317a or as otherwise agreed
  between Contrast Security and the End User. The Software may not be reverse
  engineered, modified, repackaged, sold, redistributed or otherwise used in a
  way not consistent with the End User License Agreement.
*/
'use strict';

const path = require('path');
const fs = require('fs');

// eslint-disable-next-line complexity
function getLoggerValues(option, config, tsData) {
  let tsValue, effectiveValue = config._flat[option.name];

  switch (option.name) {
    case 'agent.logger.level':
      tsValue = tsData.logLevel;
      break;
    case 'agent.logger.path':
      tsValue = tsData.logFile;
      break;
    case 'agent.security_logger.syslog.enable':
      tsValue = tsData.defend.syslog && tsData.defend.syslog.syslogEnabled;
      break;
    case 'agent.security_logger.syslog.ip':
      tsValue = tsData.defend.syslog && tsData.defend.syslog.syslogIpAddress;
      break;
    case 'agent.security_logger.syslog.port':
      tsValue = tsData.defend.syslog && tsData.defend.syslog.syslogPortNumber;
      break;
    case 'agent.security_logger.syslog.facility':
      tsValue = tsData.defend.syslog && tsData.defend.syslog.syslogFacilityCode;
      break;
    case 'agent.security_logger.syslog.severity_exploited':
      tsValue = tsData.defend.syslog && tsData.defend.syslog.syslogSeverityExploited;
      break;
    case 'agent.security_logger.syslog.severity_blocked':
      tsValue = tsData.defend.syslog && tsData.defend.syslog.syslogSeverityBlocked;
      break;
    case 'agent.security_logger.syslog.severity_probed':
      tsValue = tsData.defend.syslog && tsData.defend.syslog.syslogSeverityProbed;
      break;
    default:
      break;
  }

  if (config._sources[option.name] == 'DEFAULT' && tsValue != null) {
    effectiveValue = tsValue;
    config._sources[option.name] = 'ContrastUI';
  }

  return {
    CanonicalName: option.name,
    Name: option.name,
    Value: effectiveValue,
    Source: config._sources[option.name],
  };
}

function getAssessValues(option, config, tsData) {
  let tsValue, effectiveValue = config._flat[option.name];

  switch (option.name) {
    case 'assess.enable':
      tsValue = tsData.assess.enabled;
      break;
    case 'assess.enable_propagators':
      tsValue = tsData.assess.propagators;
      break;
    case 'assess.sampling.enable':
      tsValue = tsData.assess.sampling;
      break;
    default:
      break;
  }

  if (config._sources[option.name] == 'DEFAULT' && tsValue != null) {
    effectiveValue = tsValue;
    config._sources[option.name] = 'ContrastUI';
  }

  return {
    CanonicalName: option.name,
    Name: option.name,
    Value: effectiveValue,
    Source: config._sources[option.name],
  };
}

function getProtectValues(option, config, tsData) {
  let value = {};

  if (option.name.includes('ip-denylist')) {
    value = {
      CanonicalName: option.name.split('.')[2],
      Name: option.name,
      Value: tsData.ipDenylistsList,
      Source: 'ContrastUI',
    };
  } else if (option.name.includes('virtual-patch')) {
    value = {
      CanonicalName: option.name.split('.')[2],
      Name: option.name,
      Value: tsData.virtualPatchesList,
      Source: 'ContrastUI',
    };
  } else if (option.name.includes('protect.rules') && option.name.includes('mode')) {
    let apiRule;
    if (tsData.protectionRulesList) {
      apiRule = tsData.protectionRulesList.find(r => r.id == option.name.split('.')[2]);
    }

    const apiMode = apiRule ? apiRule.mode : undefined;
    const ymlMode = config._flat[option.name];
    let effectiveMode;

    if (!ymlMode && apiMode) {
      config._sources[option.name] = 'ContrastUI';
      effectiveMode = apiMode;
    } else if (ymlMode) {
      effectiveMode = ymlMode;
    }

    value = {
      CanonicalName: option.name.split('.')[2],
      Name: option.name,
      Value: effectiveMode,
      Source: config._sources[option.name],
    };
  }

  return value;
}

function getEffectiveConfigValues(agent, options, err) {
  const tsData = { ...agent.tsFeatureSet.serverFeatures, ...agent.tsFeatureSet.applicationSettings };
  const values = [];

  for (const option of options) {
    if (!err && option.name.includes('protect.rules') && option.name.includes('mode')) {
      // get all protect rules
      values.push(getProtectValues(option, agent.config, tsData));
    } else if (!err && option.name.includes('logger')) {
      // fetch agent/service/sys logger settings
      values.push(getLoggerValues(option, agent.config, tsData));
    } else if (!err && option.name.includes('assess')) {
      // fetch assess settings
      values.push(getAssessValues(option, agent.config, tsData));
    } else if (agent.config._flat[option.name] != null) {
      // fetch everything else
      values.push({
        CanonicalName: option.name,
        Name: option.name,
        Value: agent.config._flat[option.name],
        Source: agent.config._sources[option.name],
      });
    }
  }
  return values;
}

function getEffectiveConfig(agent, options, err) {
  const effectiveConfigValues = getEffectiveConfigValues(agent, options, err);
  const envValues = effectiveConfigValues.filter(v => v.Source == 'ENV');
  const cliValues = effectiveConfigValues.filter(v => v.Source == 'CLI');
  const ymlValues = effectiveConfigValues.filter(v => v.Source == 'YAML');
  const apiValues = effectiveConfigValues.filter(v => v.Source == 'ContrastUI');

  const effectiveConfig = {
    ReportCreate: new Date(Date.now()),
    Config: {
      EffectiveConfig: {
        Status: undefined,
        Values: effectiveConfigValues
      },
      Environment: envValues,
      CommandLine: cliValues,
      ContrastUI: apiValues,
      File: ymlValues,
    }
  };

  return effectiveConfig;
}

function outputAgentConfigFile(agent, options, args, err) {
  const effectiveConfig = getEffectiveConfig(agent, options, err);

  if (err) {
    effectiveConfig.Config.Status = 'Failure! ' +
    `Could not connect to TeamServer, so no TeamServer data will be included. Error: ${err}`;
  } else {
    effectiveConfig.Config.Status = 'Success';
  }

  try {
    fs.accessSync(path.join(args.output, '..'), fs.constants.RDWD_OK);
    fs.writeFileSync(args.output, JSON.stringify(effectiveConfig, null, 2), 'utf-8');
  } catch (err) {
    args.output = path.join(process.cwd(), 'contrast_effective_config.json');
    try {
      fs.writeFileSync(args.output, JSON.stringify(effectiveConfig, null, 2), 'utf-8');
    } catch (err) {
      console.log(`Couldn't create effective config file: ${err}`);
    }
  }

  if (!args.quiet) {
    fs.writeFileSync(1, JSON.stringify(effectiveConfig, null, 2), 'utf-8');
  }
}

module.exports = {
  getEffectiveConfigValues,
  getEffectiveConfig,
  outputAgentConfigFile,
  getProtectValues,
  getAssessValues,
  getLoggerValues
};
