# Copyright (c) 2021 Contrast Security, Inc. See https://www.contrastsecurity.com/enduser-terms-0317a for more details.
# frozen_string_literal: true

module Contrast
  module Components
    module Protect
      # A wrapper build around the Common Agent Configuration project to allow for access of the values contained in
      # its parent_configuration_spec.yaml.  Specifically, this allows for querying the state of the Protect product.
      class Interface
        include Contrast::Components::ComponentBase
        include Contrast::Components::Interface

        access_component :config, :settings

        def enabled?
          # config overrides if forcibly set
          return false if forcibly_disabled?
          return true  if forcibly_enabled?

          SETTINGS.protect_state.enabled == true
        end

        def rule_config
          CONFIG.root.protect.rules
        end

        def rules
          SETTINGS.protect_state.rules
        end

        def rule_mode rule_id
          CONFIG.root.protect.rules[rule_id]&.applicable_mode ||
              SETTINGS.application_state.modes_by_id[rule_id] ||
              Contrast::Api::Settings::ProtectionRule::Mode::NO_ACTION
        end

        def rule name
          SETTINGS.protect_state.rules[name]
        end

        def report_any_command_execution?
          if @_report_any_command_execution.nil?
            ctrl = rule_config[Contrast::Agent::Protect::Rule::CmdInjection::NAME]
            @_report_any_command_execution = true?(ctrl.disable_system_commands)
          end
          @_report_any_command_execution
        end

        def report_custom_code_sysfile_access?
          if @_report_custom_code_sysfile_access.nil?
            ctrl = rule_config[Contrast::Agent::Protect::Rule::PathTraversal::NAME]
            @_report_custom_code_sysfile_access = true?(ctrl.detect_custom_code_accessing_system_files)
          end
          @_report_custom_code_sysfile_access
        end

        def forcibly_disabled?
          @_forcibly_disabled ||= false?(CONFIG.root.protect.enable)
        end

        private

        def forcibly_enabled?
          @_forcibly_enabled ||= true?(CONFIG.root.protect.enable)
        end
      end

      COMPONENT_INTERFACE = Interface.new
    end
  end
end