#!/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 path = require('path');
const fs = require('fs');
const os = require('os');
const pkg = require('./package');
const { setup } = require('./lib/core/config/util');
const logger = require('./lib/core/logger')('contrast:system-diagnostics');

const HELP_MESSAGE = `
Description:
  The system-diagnostics utility returns the system info for the server/container the agent is running on.

Usage:
  npx -p @contrast/agent system-diagnostics --help
  npx -p @contrast/agent system-diagnostics [options]

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 isDocker = () => {
  const MOUNTINFO_REGEX = /\/docker\/containers\/(.*?)\//;
  const CGROUP_REGEX = /:\/docker\/([^/]+)$/;

  try {
    const results = fs.readFileSync('/proc/self/mountinfo', 'utf8').match(MOUNTINFO_REGEX);
    if (results) return { isDocker: true, containerID: results[1] };
  } catch (err) {
    // else check /proc/self/cgroup
  }

  try {
    const results = fs.readFileSync('/proc/self/cgroup', 'utf8').match(CGROUP_REGEX);
    if (results) return { isDocker: true, containerID: results[1] };
  } catch (err) {
    // else check /.dockerenv
  }

  try {
    const result = fs.statSync('/.dockerenv');
    if (result) return { isDocker: true, containerID: undefined };
  } catch (err) {
    // if there's not such file we can conclude it's not docker env
  }

  return { isDocker: false, containerID: undefined };
};

function isUsingPM2() {
  const used = !!process.env.pmx;
  let version = null;

  for (const pathVar of ['npm_package_json', 'PWD']) {
    const packagePath = process.env[pathVar];
    if (packagePath) {
      try {
        version = require(path.join(packagePath, 'package.json')).dependencies['pm2'];
      } catch (err) {
        //
      }
    }
    if (version) break;
  }

  return { used, version };
}

const diagnostics = {
  parseArgv(argv) {
    const args = {
      help: false,
      output: 'contrast_system_info.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 '--output':
        case '-o': {
          // 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 '--quiet':
        case '-q':
          args.quiet = true;
          break;
        default:
          if (!arg.startsWith('-')) {
            args.entry = arg;
          }
          break;
      }
    }

    return args;
  },

  outputSystemInfo(args, info) {
    try {
      fs.accessSync(path.join(args.output, '..'), fs.constants.RDWD_OK);
      fs.writeFileSync(args.output, JSON.stringify(info, null, 2), 'utf-8');
    } catch (err) {
      console.log(`Couldn't create system info file: ${err}`);
    }

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

  fetchSystemInfo() {
    const yaml = setup({}, logger);
    const appPath = process.cwd();

    const info = {
      ReportDate: new Date(),
      MachineName: os.hostname(),
      Contrast: {
        Url: yaml.api.url,
        Proxy: yaml.api.proxy,
        Server: {
          Name: yaml._flat['server.name'],
        },
        Agent: {
          Name: '@contrast/agent',
          Version: pkg.version,
        },
      },
      Node: {
        Version: process.version
      },
      OperatingSystem: {
        Architecture: os.arch(),
        Name: os.type(),
        Version: os.release(),
        KernelVersion: os.version(),
        CPU: {
          type: os.cpus()[0].model,
          count: os.cpus().length,
        }
      },
      Host: {
        Docker: isDocker(),
        PM2: isUsingPM2(),
        Memory: {
          Total: (os.totalmem() / 1e6).toFixed(0).concat(' MB'),
          Free: (os.freemem() / 1e6).toFixed(0).concat(' MB'),
          Used: ((os.totalmem() - os.freemem()) / 1e6).toFixed(0).concat(' MB'),
        }
      },
      Application: appPath ? require(path.join(appPath, 'package.json')) : null,
    };

    return info;
  }
};
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));

  if (args.help) {
    console.log(HELP_MESSAGE);
  } else {
    const info = diagnostics.fetchSystemInfo();
    diagnostics.outputSystemInfo(args, info);
  }
}
