require 'qu/tasks'

namespace :qu do
  desc "Start Qu Scheduler"
  task :scheduler => :scheduler_setup do
    require 'qu'
    require 'qu-scheduler'

    if ENV['BACKGROUND']
      unless Process.respond_to?('daemon')
        abort "Environment variable BACKGROUND is set, which requires ruby >= 1.9"
      end
      Process.daemon(true)
    end

    File.open(ENV['PIDFILE'], 'w') { |f| f << Process.pid.to_s } if ENV['PIDFILE']

    Qu::Scheduler.dynamic = true if ENV['DYNAMIC_SCHEDULE']
    Qu::Scheduler.run
  end

  task :scheduler_setup do
    if ENV['INITIALIZER_PATH']
      load ENV['INITIALIZER_PATH'].to_s.strip
    else
      Rake::Task['qu:setup'].invoke
    end
  end

  # No-op task in case it doesn't already exist
  task :setup
end

# Convenience tasks compatibility
task 'resque:scheduler' => 'qu:scheduler'
