#!/usr/bin/env ruby

require 'optparse'
require 'rapns'

environment = ARGV[0]

config = Rapns::ConfigurationWithoutDefaults.new

options = ARGV.options do |opts|
  opts.banner = 'Usage: rapns <Rails environment> [options]'
  opts.on('-f', '--foreground', 'Run in the foreground.') { config.foreground = true }
  opts.on('-P N', '--db-poll N', Integer, "Frequency in seconds to check for new notifications.") { |n| config.push_poll = n }
  opts.on('-F N', '--feedback-poll N', Integer, "Frequency in seconds to check for feedback.") { |n| config.feedback_poll = n }
  opts.on('-e', '--no-error-checks', 'Disable APNs error checking after notification delivery.') { config.check_for_errors = false }
  opts.on('-n', '--no-airbrake-notify', 'Disables error notifications via Airbrake.') { config.airbrake_notify = false }
  opts.on('-p PATH', '--pid-file PATH', String, 'Path to write PID file. Relative to Rails root unless absolute.') { |path| config.pid_file = path }
  opts.on('-b N', '--batch-size N', Integer, 'Storage backend notification batch size.') { |n| config.batch_size = n }
  opts.on('-B', '--[no-]batch-storage-updates', 'Perform storage updates in batches.') { |v| config.batch_storage_updates = v }
  opts.on('-v', '--version', 'Print the version.') { puts "rapns #{Rapns::VERSION}"; exit }
  opts.on('-h', '--help', 'You\'re looking at it.') { puts opts; exit }
end

if environment.nil? || environment =~ /^-/
  puts options.to_s
  exit 1
end

options.parse!

ENV['RAILS_ENV'] = environment
load 'config/environment.rb'
load 'config/initializers/rapns.rb' if File.exist?('config/initializers/rapns.rb')

Rapns.config.update(config)
Rapns.require_for_daemon
Rapns::Daemon.start
