<commit_before>require "spec_helper"
require "support/shared/integration/integration_helper"
require "chef/mixin/shell_out"
require "tiny_server"
require "tmpdir"
require "chef-utils/dist"
require "chef/mixin/powershell_exec"

# cspell:disable-next-line
SOME_CHARS = "~!@#%^&*_-+=`|\\(){}[<]:;'>,.?/0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ_abcdefghijklmnopqrstuvwxyz".each_char.to_a.freeze

describe "chef-client" do

  def recipes_filename
    File.join(CHEF_SPEC_DATA, "recipes.tgz")
  end

  def start_tiny_server(**server_opts)
    @server = TinyServer::Manager.new(**server_opts)
    @server.start
    @api = TinyServer::API.instance
    @api.clear
    #
    # trivial endpoints
    #
    # just a normal file
    # (expected_content should be uncompressed)
    @api.get("/recipes.tgz", 200) do
      File.binread(recipes_filename)
    end
  end

  def stop_tiny_server
    @server.stop
    @server = @api = nil
  end

  def install_certificate_in_store(client_name)
    if ChefUtils.windows?
      powershell_exec! <<~EOH
        if (-not (($PSVersionTable.PSVersion.Major -ge 5) -and ($PSVersionTable.PSVersion.Build -ge 22000)) ) {
          New-SelfSignedCertificate -CertStoreLocation Cert:\\LocalMachine\\My -DnsName "#{client_name}"
        }
        else {
          New-SelfSignedCertificate -CertStoreLocation Cert:\\LocalMachine\\My -Subject "#{client_name}" -FriendlyName "#{client_name}" -KeyExportPolicy Exportable
        }
      EOH
    end
  end

  def create_registry_key
    ::Chef::HTTP::Authenticator.get_cert_password
    # @win32registry = Chef::Win32::Registry.new
    # path = "HKEY_LOCAL_MACHINE\\Software\\Progress\\Authentication"
    # unless @win32registry.key_exists?(path)
    #   @win32registry.create_key(path, true)
    # end
    # password = SOME_CHARS.sample(1 + rand(SOME_CHARS.count)).join[0...14]
    # values = { name: "PfxPass", type: :string, data: password }
    # @win32registry.set_value(path, values)
  end

  def remove_certificate_from_store
    powershell_exec! <<~EOH
      Get-ChildItem -path cert:\\LocalMachine\\My -Recurse -Force  | Where-Object { $_.Subject -Match "#{client_name}" } -ErrorAction Stop | Remove-Item
    EOH
  end

  def remove_registry_key
    powershell_exec!("Remove-ItemProperty -Path HKLM:\\SOFTWARE\\Progress\\Authentication -Name 'PfxPass' ")
  end

  def verify_export_password_exists
    powershell_exec! <<~EOH
    Try {
      if (-not (($PSVersionTable.PSVersion.Major -ge 5) -and ($PSVersionTable.PSVersion.Build -ge 22000)) ) {
        $response = Get-ItemProperty -Path "HKLM:\\Software\\Progress\\Authentication" -Name "PfxPass" -ErrorAction Stop
        }
      else {
        $response = Get-ItemPropertyValue -Path "HKLM:\\Software\\Progress\\Authentication" -Name "PfxPass" -ErrorAction Stop
        }
      if ($response) {return $true}
      }
    Catch {
        return $false
    }
    EOH
  end

  include IntegrationSupport
  include Chef::Mixin::ShellOut
  include Chef::Mixin::PowershellExec

  let(:chef_dir) { File.join(__dir__, "..", "..", "..") }

  # Invoke `chef-client` as `ruby PATH/TO/chef-client`. This ensures the
  # following constraints are satisfied:
  # * Windows: windows can only run batch scripts as bare executables. Rubygems
  # creates batch wrappers for installed gems, but we don't have batch wrappers
  # in the source tree.
  # * Other `chef-client` in PATH: A common case is running the tests on a
  # machine that has omnibus chef installed. In that case we need to ensure
  # we're running `chef-client` from the source tree and not the external one.
  # cf. CHEF-4914<commit_msg>Refactored tests for older Windows versions<commit_after>require "spec_helper"
require "support/shared/integration/integration_helper"
require "chef/mixin/shell_out"
require "tiny_server"
require "tmpdir"
require "chef-utils/dist"
require "chef/mixin/powershell_exec"

# cspell:disable-next-line
SOME_CHARS = "~!@#%^&*_-+=`|\\(){}[<]:;'>,.?/0123456789ABCDEFGHIJKLMNOPQRSTUVWXYZ_abcdefghijklmnopqrstuvwxyz".each_char.to_a.freeze

describe "chef-client" do

  def recipes_filename
    File.join(CHEF_SPEC_DATA, "recipes.tgz")
  end

  def start_tiny_server(**server_opts)
    @server = TinyServer::Manager.new(**server_opts)
    @server.start
    @api = TinyServer::API.instance
    @api.clear
    #
    # trivial endpoints
    #
    # just a normal file
    # (expected_content should be uncompressed)
    @api.get("/recipes.tgz", 200) do
      File.binread(recipes_filename)
    end
  end

  def stop_tiny_server
    @server.stop
    @server = @api = nil
  end

  def install_certificate_in_store(client_name)
    if ChefUtils.windows?
      powershell_exec! <<~EOH
        if (-not (($PSVersionTable.PSVersion.Major -ge 5) -and ($PSVersionTable.PSVersion.Build -ge 22000)) ) {
          New-SelfSignedCertificate -CertStoreLocation Cert:\\LocalMachine\\My -DnsName "#{client_name}"
        }
        else {
          New-SelfSignedCertificate -CertStoreLocation Cert:\\LocalMachine\\My -Subject "#{client_name}" -FriendlyName "#{client_name}" -KeyExportPolicy Exportable
        }
      EOH
    end
  end

  def create_registry_key
    ::Chef::HTTP::Authenticator.get_cert_password
    # @win32registry = Chef::Win32::Registry.new
    # path = "HKEY_LOCAL_MACHINE\\Software\\Progress\\Authentication"
    # unless @win32registry.key_exists?(path)
    #   @win32registry.create_key(path, true)
    # end
    # password = SOME_CHARS.sample(1 + rand(SOME_CHARS.count)).join[0...14]
    # values = { name: "PfxPass", type: :string, data: password }
    # @win32registry.set_value(path, values)
  end

  def remove_certificate_from_store
    powershell_exec! <<~EOH
      Get-ChildItem -path cert:\\LocalMachine\\My -Recurse -Force  | Where-Object { $_.Subject -Match "#{client_name}" } -ErrorAction Stop | Remove-Item
    EOH
  end

  def remove_registry_key
    powershell_exec!("Remove-ItemProperty -Path HKLM:\\SOFTWARE\\Progress\\Authentication -Name 'PfxPass' ")
  end

  def verify_export_password_exists
    powershell_exec! <<~EOH
    Try {
      $response = Get-ItemProperty -Path "HKLM:\\Software\\Progress\\Authentication" -Name "PfxPass" -ErrorAction Stop
      if ($response) {return $true}
      }
    Catch {
        return $false
    }
    EOH
  end

  include IntegrationSupport
  include Chef::Mixin::ShellOut
  include Chef::Mixin::PowershellExec

  let(:chef_dir) { File.join(__dir__, "..", "..", "..") }

  # Invoke `chef-client` as `ruby PATH/TO/chef-client`. This ensures the
  # following constraints are satisfied:
  # * Windows: windows can only run batch scripts as bare executables. Rubygems
  # creates batch wrappers for installed gems, but we don't have batch wrappers
  # in the source tree.
  # * Other `chef-client` in PATH: A common case is running the tests on a
  # machine that has omnibus chef installed. In that case we need to ensure
  # we're running `chef-client` from the source tree and not the external one.
  # cf. CHEF-4914
{'fraction_non_alphanumeric': 0.12111222588505088, 'fraction_numerical': 0.011466246237637954, 'mean_word_length': 3.467349551856594, 'pattern_counts': {'":': 0, '<': 17, '<?xml version=': 0, '>': 5, 'https://': 0, 'lorem ipsum': 0, 'www.': 0, 'xml': 0}, 'pii_count': 0, 'substrings_counts': 0, 'word_list_counts': {'cursed_substrings.json': 0, 'profanity_word_list.json': 0, 'sexual_word_list.json': 0, 'zh_pornsignals.json': 0}}
{'dir': 'git-commits-cleaned', 'id': '2873942', 'n_tokens_mistral': 2427, 'n_tokens_neox': 2260, 'n_words': 520}