require 'rake/contrib/rubyforgepublisher'
require 'rake/gempackagetask'
require 'rake/rdoctask'
require 'rake/testtask'
require 'webrick'

WEBRICK_PID_FILE = 'webrick/pid'
WEBRICK_LOG_FILE = 'webrick/log'

gem_spec = Gem::Specification.new do |s|
  s.add_dependency 'mime', '>=0.1.0'
  s.name = 'thin_http'
  s.version = '0.1.1'
  s.summary = 'Lightweight and user-friendly HTTP client library'
  s.test_files = FileList['test/*_test.rb']
  s.files = FileList['README', 'Rakefile', 'lib/**/*.rb', 'test/**/*']
  s.author = 'Clint Pachl'
  s.email = 'pachl@ecentryx.com'
  s.homepage = 'http://thinhttp.rubyforge.org/'
  s.rubyforge_project = 'thinhttp'
  s.has_rdoc = true
end


Rake::GemPackageTask.new(gem_spec) do |pkg|
  pkg.need_tar_gz = true
end

Rake::RDocTask.new do |rd|
    rd.rdoc_files.include('README', 'lib/')
    rd.rdoc_dir = 'html'  # :publish task looks here
    rd.main = 'README'
    rd.options << '--all' << '--inline-source'
end

Rake::TestTask.new do |t|
  t.libs << 'lib' << 'test'
  t.pattern = 'test/*_test.rb'
  t.warning = true
end

desc 'Publish docs to RubyForge'
task :publish => [:rerdoc] do
  Rake::RubyForgePublisher.new('thinhttp', 'pachl').upload
end

namespace :webrick do

  desc 'Start WEBrick (run before test task)'
  task :start do
  
    if File.exist?(WEBRICK_PID_FILE)
      puts "Already running (if not, remove '#{WEBRICK_PID_FILE}')."
    else
      webrick_pid = fork do
        STDERR.reopen(WEBRICK_LOG_FILE, "w")
      
        s = WEBrick::HTTPServer.new(
          :DocumentRoot => Dir::pwd + '/test/scaffold/htdocs',
          :Port => ENV['WEBRICK_PORT'] || 2000
        )
      
        trap('INT') {s.shutdown}
        s.logger.info "Root=#{s.config[:DocumentRoot]}"
        s.start
      end
    
      open(WEBRICK_PID_FILE, 'w') {|f| f << webrick_pid}
    end
  
  end
  
  desc 'Stop WEBrick (run after test task)'
  task :stop do
    if File.exist?(WEBRICK_PID_FILE)
      webrick_pid = IO.read(WEBRICK_PID_FILE).to_i
      Process.kill('INT', webrick_pid)
      FileUtils.rm(WEBRICK_PID_FILE)
    end
  end

end
