require "ruby_installer/runtime"

begin
  checkfile = File.join(Gem.default_dir, "/writable_p")
  File.write(checkfile, "")
  File.unlink(checkfile) rescue nil # Raises ENOENT sometimes
rescue Errno::EACCES
  warn_per_user = true
  module Gem
    class << self
      # Hack to prevent method redefinition warning
      alias_method :operating_system_defaults, :operating_system_defaults

      # Set default options for the gem command
      def operating_system_defaults
        defaults = ["--install-dir", Gem.user_dir]
        bindir = File.join(Gem.user_home, 'AppData/Local/Microsoft/WindowsApps')
        defaults += ["--bindir", bindir] if File.directory?(bindir)
        { 'gem' => defaults }
      end
    end
  end
  # Set default options for the bundle command
  ENV['GEM_HOME'] ||= Gem.user_dir
  bindir = File.join(Gem.user_home, 'AppData/Local/Microsoft/WindowsApps')
  ENV['BUNDLE_SYSTEM_BINDIR'] ||= bindir if File.directory?(bindir)
rescue => err
  warn RubyInstaller::Runtime::Colors.yellow("Warning: Can't determine writability of default gem path: #{err}")
end

RubyInstaller::Runtime.enable_dll_search_paths

Gem.pre_install do |gem_installer|
  if warn_per_user
    Gem.ui.say(RubyInstaller::Runtime::Colors.green("Using rubygems directory: #{Gem.user_dir}"))
    warn_per_user = false
  end

  RubyInstaller::Runtime.enable_msys_apps(for_gem_install: true) unless gem_installer.spec.extensions.empty?

  if !gem_installer.options || !gem_installer.options[:ignore_dependencies] || gem_installer.class.to_s.include?("Bundler")
    [['msys2_dependencies'      , :install_packages      ],
     ['msys2_mingw_dependencies', :install_mingw_packages]].each do |metakey, func|

      if deps=gem_installer.spec.metadata[metakey]
        begin
          RubyInstaller::Runtime.msys2_installation.send(func, deps.split(" "), verbose: Gem.configuration.verbose)
        rescue RubyInstaller::Runtime::Msys2Installation::CommandError => err
          Gem.ui.say(err.to_s)
        end
      end
    end
  end
end

begin
  config_dir = ENV['ProgramData']
  if config_dir && !File.exist?(config_fname = File.join(config_dir, "gemrc"))
    File.open(config_fname, File::CREAT | File::EXCL | File::WRONLY) do |fd|
      fd.write <<-EOT
# This is the system wide config file for Rubygems.
# It is generated by RubyInstaller as a security measure.
# Feel free to add any rubygems config options as described on:
#    https://docs.ruby-lang.org/en/3.1/Gem/ConfigFile.html
# But do not delete this file as otherwise it could be hijacked by
# another user in a multi-user environment.
---
verbose: false
      EOT
    end
  end
rescue => err
  warn RubyInstaller::Runtime::Colors.yellow("Warning: Failed to create a system wide 'gemrc' file, making Rubygems possibly insecure: #{err}")
end
