#!/usr/bin/env ruby

if ARGV.length == 0 || ARGV.first == 'help'
  $stderr.puts "usage: run_urls iterations option_1 ... option_n"
  $stderr.puts "example: run_urls 100 -bm=default -log | grep Status:"
  exit 1
end

unless ENV['RAILS_ROOT']
  if File.directory?("config") && File.exists?("config/environment.rb")
    ENV['RAILS_ROOT'] = File.expand_path(".")
  else
    $stderr.puts("#{File.basename $PROGRAM_NAME}: $RAILS_ROOT not set and could not be configured automatically")
    exit 1
  end
end

$:.unshift(File.expand_path(File.dirname(__FILE__) + '/../lib'))
require 'railsbench/railsbenchmark'
require ENV['RAILS_ROOT'] + '/config/benchmarks'

trap("INT") do
  $stderr.print "clearing database connections ..."
  ActiveRecord::Base.send :clear_all_cached_connections! if ActiveRecord::Base.respond_to?(:clear_all_cached_connections)
  ActiveRecord::Base.send :clear_all_connections! if ActiveRecord::Base.respond_to?(:clear_all_connections)
  $stderr.puts
  $stderr.puts "benchmarking aborted!"
  exit!(-1)
end

benchmark_name = "default"
ARGV.each{ |arg| benchmark_name = $1 if arg =~ /-bm=([^ ]+)/ }

RAILS_BENCHMARKER.iterations = ARGV[0].to_i
RAILS_BENCHMARKER.setup_test_urls(benchmark_name)
RAILS_BENCHMARKER.establish_test_session
RAILS_BENCHMARKER.warmup if ARGV.include?('-warmup')
RAILS_BENCHMARKER.run_urls_without_benchmark(ENV['RUBY_GC_STATS'].to_i == 1 ||
                                             (GC.respond_to?(:trace_enabled?) && GC.trace_enabled?))

__END__

#  Copyright (C) 2005-2008  Stefan Kaes
#
#  This program is free software; you can redistribute it and/or modify
#  it under the terms of the GNU General Public License as published by
#  the Free Software Foundation; either version 2 of the License, or
#  (at your option) any later version.
#
#  This program is distributed in the hope that it will be useful,
#  but WITHOUT ANY WARRANTY; without even the implied warranty of
#  MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#  GNU General Public License for more details.
#
#  You should have received a copy of the GNU General Public License
#  along with this program; if not, write to the Free Software
#  Foundation, Inc., 51 Franklin St, Fifth Floor, Boston, MA 02110-1301 USA
