# Maybe this could be done more elegantly with File#flock
class FileMutex

  def initialize(path)
    @path = path
  end

  def acquire(&block)
    wait
    begin
      take!
      block.call
    ensure
      # Ensure the mutex file gets deleted even if the test failed, raised an error
      # or if the user terminated the scenario with CTRL+C or kill.
      release
    end
  end

  def release
    File.delete(@path) if taken?
  end

  private

  def taken?
    File.exists?(@path)
  end

  def wait
    sleep(0.1) while taken?
  end

  def take!
    File.open(MUTEX_PATH, "w") {}
  end

end


NO_PARALLEL_MUTEX = FileMutex.new("tmp/cucumber_no_parallel")

# In case a previous test process that held the mutex was killed the hard way
# we clean out the mutex file on the next test run, if we are the first parallel_test
# process.
if ENV['TEST_ENV_NUMBER'].blank?
  NO_PARALLEL_MUTEX.release
end

Around("@no_parallel") do |scenario, block|
  NO_PARALLEL_MUTEX.acquire(&block)
end
