/**
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 patcher = require('../../../hooks/patcher');
const tracker = require('../../../tracker');
const { PATCH_TYPES } = require('../../../constants');
const moduleHook = require('../../../hooks/require');
const { createSubsetTagRanges } = require('../../propagators/manager');
const { PropagationEvent, Signature, CallContext } = require('../../models');

/**
 * Entry point to propagator provider
 * This instruments path.basename on
 * both win32 and posix keys
 */
module.exports.handle = function handle() {
  // we can reuse these value objects in various calls/models
  const signature = new Signature('path.extname');
  const params = [
    { index: 0, type: 'start' },
    { index: 1, inclusive: true, type: 'stop' }
  ];

  moduleHook.resolve({ name: 'path' }, (path) => {
    for (const os of ['posix', 'win32']) {
      patcher.patch(path[os], 'basename', {
        name: `path.${os}.basename`,
        patchType: PATCH_TYPES.ASSESS_PROPAGATOR,
        post(data) {
          const [path, extension] = data.args;
          let _path = path;
          if (!path || !data.result) return;

          const trackingData = tracker.getData(path);
          if (!trackingData) return;

          if (extension) {
            const extIndex = _path.lastIndexOf(extension);
            if (extIndex > -1) {
              _path = _path.substr(0, _path.lastIndexOf(extension));
            }
          }

          // path.basename() implementation does a slice
          const tagRanges = createSubsetTagRanges({
            sourceTagRanges: trackingData.tagRanges,
            data: {
              args: getSliceArgs(data)
            },
            params,
            sources: [_path],
            target: data.result
          });

          // no tags propagated to the result
          if (!tagRanges.length) return;

          const parentEvent = trackingData.event;
          const tracked = tracker.track(data.result);
          if (tracked) {
            tracked.props.tagRanges = tagRanges;
            tracked.props.event = new PropagationEvent({
              context: CallContext.create(data),
              parents: [parentEvent],
              signature,
              source: 'P',
              tagRanges,
              target: 'R'
            });
            data.result = tracked.str;
          }
        }
      });
    }
  });
};

/**
 * Based on the input and return value, calculates the slice args used by node's
 * implementation of `path.basename()`.
 */
function getSliceArgs(data) {
  const {
    args: [path, extension],
    result
  } = data;
  const baseAndExt = `${result}${extension}`;

  if (extension && path.endsWith(baseAndExt)) {
    // path.basename('/path/mov.mov', '.mov') => 'mov'
    return [path.lastIndexOf(baseAndExt), path.length - extension.length];
  } else {
    // path.basename('/path/.mov', '.mov') => '.mov'
    // path.basename('/path/mov.mov', '.movie') => 'mov.mov'
    // path.basename('/path/mov.mov') => 'mov.mov'
    // path.basename('/path/.mov') => '.mov'
    // path.basename('/path/mov') => 'mov'
    return [path.lastIndexOf(result), path.length];
  }
}
