/**
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 startTime = process.hrtime();

const Module = require('module');
const loader = require('./agent-loader');
const orig = Module.runMain;

/**
 * Calling contrast bootstrapping
 * process before invoking the main
 * script from cli
 */
Module.runMain = async function (...args) {
  const { isMainThread } = require('worker_threads');

  try {
    // Skip instrumenting worker threads.
    if (!isMainThread) {
      orig.apply(this, args);

      return;
    }

    const { enabled } = await loader.init(process.argv);
    if (enabled) {
      await loader.bootstrap(process.argv);
    }
    await loader.resetArgs(process.argv[0], process.argv[1]);

    const diagnostics = process.env['CONTRAST__AGENT__DIAGNOSTICS__ENABLE'];
    if (diagnostics === 'true') {
      // Delay just a little bit, so the console.log() in config-diagnostics can finish
      // Might wanna look for a better solution
      setTimeout(() => {
        // eslint-disable-next-line no-process-exit
        process.exit(0);
      }, 100); // not sure why so long, in v5 it only needed 5ms more
    }

    loader.logTime(startTime, 'agent');
    const appStartTime = process.hrtime();
    orig.apply(this, args);
    loader.logTime(appStartTime, 'application');
    loader.logTime(startTime, 'agent & application');
  } catch (err) {
    console.error(err);
    process.exit(-1); // eslint-disable-line no-process-exit

  }
};
