class Dunlop::ExecutionBatchPid

  PIDDIR = Rails.root.join("tmp/pids")

  def initialize(id=nil)
    @id = id
  end

  def lock
    raise "lock already taken" if locked?
    begin
      claim_lock
      yield
    ensure
      release_lock
    end
  end

  def locked?
    File.exist?(pidfile)
  end

  private

  def pidfile
    filename = if @id.blank?
      "rake_fab_run_batch.pid"
    else
      "rake_fab_run_batch_#{Shellwords.escape(@id)}.pid"
    end
    File.join(PIDDIR, filename)
  end


  def claim_lock
    FileUtils.mkdir_p(PIDDIR)
    File.open( pidfile, "w" ) do |file|
      file << Process.pid || 'dummy'
    end
    return true
  end

  def release_lock
    FileUtils.rm_f(pidfile)
  end

end
