#!/usr/bin/env ruby
# frozen_string_literal: true

#
# This file was generated by Bundler.
#
# The application's executable is in bin/bundle.
#

require "rubygems"

m = Module.new do
  module_function

  def invoked_as_script?
    File.expand_path($0) == File.expand_path(__FILE__)
  end

  def env_var_version
    ENV["BUNDLER_VERSION"]
  end

  def cli_arg_version
    return unless invoked_as_script?
    return unless "--version" == ARGV.first
    bundler_version = nil
    update_index = nil
    ARGV.each_with_index do |a, i|
      bundler_version = a if update_index && update_index.succ == i
      next unless a =~ /\A--bundler\z/
      update_index = i
    end
    bundler_version
  end

  def gemfile
    gemfile = ENV["BUNDLE_GEMFILE"]
    return gemfile if gemfile && !gemfile.empty?
    File.expand_path("../Gemfile", __dir__)
  end

  def lockfile
    lockfile = "#{gemfile}.lock"
    return lockfile if File.exist?(lockfile)
    nil
  end

  def bundler_version
    @bundler_version ||=
      env_var_version || cli_arg_version ||
      lockfile_version
  end

  def lockfile_version
    return unless lockfile
    lockfile_contents = File.read(lockfile)
    return unless lockfile_contents =~ /\n\nBUNDLED WITH\n\s*(#{Gem::Version::VERSION_PATTERN})\n/
    Regexp.last_match(1)
  end

  def load_bundler!
    $LOAD_PATH.unshift(bundler_spec.lib_dirs_glob) if bundler_spec
    require "bundler"
    unless bundler_spec
      Gem::GemRunner.new.run(["install", "bundler", "--version", bundler_version]) if bundler_version
      require "bundler"
    end
  end

  def bundler_spec
    @bundler_spec ||= Gem::Specification.find_by_name("bundler", bundler_version)
  rescue Gem::MissingSpecVersionError, Gem::MissingSpecError
    nil
  end
end

m.load_bundler!

if m.invoked_as_script?
  load Gem.bin_path("bundler", "bundle")
end
