#!/usr/bin/env ruby

require "pathname"

class GuardReloader
  class Config
    def using_rubygems?
      ENV["RUBYGEMS_GEMDEPS"]
    end

    def setup_rubygems_for_deps
      require "rubygems"
    end

    def current_bundler_gemfile
      ENV["BUNDLE_GEMFILE"]
    end

    def using_bundler?
      ENV["BUNDLE_GEMFILE"]
    end

    def setup_bundler_env(gemfile)
      ENV["BUNDLE_GEMFILE"] = gemfile
    end

    def setup_bundler
      require "rubygems"
      require "bundler/setup"
    end

    def program_path
      Pathname(__FILE__)
    end

    def program_arguments
      ARGV
    end

    def windows?
      Gem.win_platform?
    end

    def exit_with(code)
      exit(code)
    end

    def spawn_with(*args)
      spawn(*args)
    end

    def wait_ignoring_interrupts(pid)
      Process.wait2(pid)[1].exitstatus
    rescue Interrupt
      retry
    rescue Errno::ECHILD
      1
    end

    def exist?(path)
      path.exist?
    end

    def guard_core_path
      Gem.bin_path("guard", "_guard-core")
    end
  end

  attr_reader :config
  def initialize(config)
    @config = config
  end

  def setup
    return config.setup_bundler if config.using_bundler?
    return config.setup_rubygems_for_deps if config.using_rubygems?

    # No dependency management detected - check if binstubbed by bundler
    relative_to_binstub = config.program_path + "../../Gemfile"
    if config.exist?(relative_to_binstub)
      config.setup_bundler_env(relative_to_binstub.to_s)
      config.setup_bundler
      return
    end

    unless config.exist?(Pathname("Gemfile"))
      # Running guard with bare ruby here - it's up to the user
      # to setup/install missing deps
      return
    end

    STDERR.puts "Warning: you have a Gemfile, but you're not using"\
      " bundler or RUBYGEMS_GEMDEPS"
  end

  def auto_restart
    args = [Gem.ruby, config.guard_core_path] + config.program_arguments

    loop do
      exitcode = config.wait_ignoring_interrupts(config.spawn_with(*args))
      config.exit_with(exitcode) if exitcode != 2
    end
  end
end

unless ENV["GUARD_SPECS_RUNNING"]
  config = GuardReloader::Config.new
  reloader = GuardReloader.new(config)
  reloader.setup
  reloader.auto_restart
end
