# Jobs code lists extracted to constants for easier testing.
# See config/jobs.rb for details.
#
# TODO - this is kind of hack ... remove it
require File.expand_path(File.join(File.dirname(__FILE__), 'jobs'))

env :PATH, '/home/bender/bin:/home/bender/.rvm/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games'

set :output, { standard: '/var/log/cron.output' }
env :MAILTO, 'system-dev+cron@3scale.net'

bundle_path = ENV.fetch('BUNDLE_BIN_PATH') { `which bundle`.strip }

set :bundle_command, "#{Gem.ruby} #{bundle_path} exec"
set :runner_command, "#{Gem.ruby} script/rails runner"
set :rake_command, "#{Gem.ruby} #{`which rake`.strip}"
set :ruby_command, Gem.ruby

job_type :rake, "cd :path && :environment_variable=:environment :bundle_command :rake_command :task --silent :output"
job_type :ruby, "cd :path && :bundle_command :ruby_command :task :output"

job_proc = Proc.new do |task|
  if task.respond_to? :each_pair
    # then specifies whenever command and task to run
    task.each_pair do |command, task|
      send command, task
    end
  # else if it is like string, run it as runner
  elsif task.respond_to? :to_str
    runner "ThreeScale::Jobs.run(#{task.inspect}) { #{task} }"
  end
end

every :month, roles: [:cron] do
  ThreeScale::Jobs::MONTH.each { |task| job_proc.call(task) }
end

every :week, roles: [:cron] do
  ThreeScale::Jobs::WEEK.each { |task| job_proc.call(task) }
end

every :hour, roles: [:cron] do
  ThreeScale::Jobs::HOUR.each { |task| job_proc.call(task) }
end

every :monday, roles: [:cron] do
  ThreeScale::Jobs::MAGICAL_GUILLAUME_WEEKLY_JOBS.each { |task| job_proc.call(task) }
end

every '20 0 1 * *' , roles: [:cron] do
  ThreeScale::Jobs::MAGICAL_GUILLAUME_WEEKLY_JOBS.each { |task| job_proc.call(task) }
end

ThreeScale::Jobs::DAILY.each_with_index do |task, index|
  every :day, at: "#{8+index}:00", roles: [:cron] do
    job_proc.call(task)
  end
end

every :day, :at => '08:00', roles: [:cron] do
  ThreeScale::Jobs::BILLING.each { |task| job_proc.call(task) }
end

ThreeScale::Jobs::CUSTOM.each_pair do |interval, task|
  every interval, roles: [:cron] do
    job_proc.call(task)
  end
end

every 1.day, :at => '2:00 pm' do
  rake 'ts:index'
end

# every hour would put at minute 0 which is quite busy with tasks already
every '42 * * * *' do
  rake 'ts:in:delta'
end
