#!/usr/bin/env node
/**
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 { exec } = require('child_process');
const path = require('path');

const HELP_MESSAGE = `
Description:
  The config-diagnostics utility returns the current effective node agent configuration.

Usage:
  npx -p @contrast/agent config-diagnostics <path/to/entry/script> [options]
  npx -p @contrast/agent config-diagnostics --help

Options:
  --quiet      -q     Prevents output of the report to the console.
  --output     -o     The directory to write the report in. Defaults to the current directory.
`;

const diagnostics = {
  parseArgv(argv) {
    const args = {
      help: false,
      output: 'contrast_effective_config.json',
      quiet: false,
    };

    for (let i = 0; i < argv.length; i++) {
      const arg = argv[i];
      switch (arg) {
        case '--help':
          args.help = true;
          return args;
        case '-o':
        case '--output': {
          // grab the next value and skip in the next loop
          const output = argv[++i];
          if (!output) {
            throw new Error('Expected a value to be provided after --output');
          }
          args.output = output;
          break;
        }
        case '-q':
        case '--quiet':
          args.quiet = true;
          break;
        default:
          if (!arg.startsWith('-')) {
            args.entry = arg;
          }
          break;
      }
    }

    if (!args.entry) {
      throw new Error('No entry point provided');
    }

    return args;
  },

  executeNodeAgent(args) {
    let agentEnvArgs =
      'CONTRAST__SHOW__BANNER=false ' +
      'CONTRAST__AGENT__DIAGNOSTICS__ENABLE=true ';

    if (!args.quiet) {
      agentEnvArgs = `${agentEnvArgs} CONTRAST__AGENT__DIAGNOSTICS__QUIET=false`;
    }

    if (args.output) {
      agentEnvArgs = `${agentEnvArgs} CONTRAST__AGENT__DIAGNOSTICS__REPORT_PATH=${args.output}`;
    }

    const bootstrap = path.join(__dirname, 'bootstrap.js');
    const command = `${agentEnvArgs} node -r ${bootstrap} ${args.entry}`;

    exec(command, (error, stdout, stderr) => {
      if (error && !args.quiet) {
        console.log(`error: ${error.message}`);
        return;
      }

      // by default errors still won't be visible since stdout == sterr
      if (stderr) {
        console.log(`stderr: ${stderr}`);
        return;
      }

      if (!args.quiet) {
        console.log(stdout);
      }
    });
  },

  fetchAgentConfig(args) {
    if (args.help) {
      console.log(HELP_MESSAGE);
    } else {
      this.executeNodeAgent(args);
    }
  },
};

module.exports = diagnostics;

// only run if this file is being executed as an entry script
// istanbul ignore next
if (require.main === module) {
  const args = diagnostics.parseArgv(process.argv.slice(2));
  diagnostics.fetchAgentConfig(args);
}
