#!/usr/bin/env ruby

require "optparse"

options = {}
ARGV.options do |opt|
  opt.on("-d", "--daemon", "Run daemonized in the background") { |v| options[:daemon] = v }
  opt.on("-f", "--force", "Crawl all feeds regardless of the crawler's status") { |v| options[:force] = v }
  opt.on("-l", "--log=FILE", "Where to write log messages") { |v| options[:log_file] = v }
  opt.on("-p", "--pid=FILE", "Where to write the PID") { |v| options[:pid_file] = v }
  opt.on("-e", "--environment=NAME", "Specifies the environment to run this server under (test/development/production)") { |v| ENV['RAILS_ENV'] = v }
  opt.parse!
end

require File.dirname(__FILE__) + '/../config/environment'
require "fastladder/crawler"

if options[:daemon]
  options[:log_file] ||= "#{RAILS_ROOT}/log/crawler.log" if options[:daemon]
  exit!(0) if fork
  Process::setsid
  pidfile = options[:pid_file] || File.join(RAILS_ROOT, 'tmp', 'pids', 'crawler.pid')
  exit!(0) if fork
  open(pidfile, 'w') { |f| f << Process.pid }
  Dir::chdir('/')
  File::umask(0)
  STDIN.reopen('/dev/null')
  STDOUT.reopen('/dev/null', 'w')
  STDERR.reopen('/dev/null', 'w')
end

Fastladder::Crawler.start(options)
begin
  File.delete(options[:pid_file]) if File.exists?(options[:pid_file])
rescue
end
