$:.unshift('lib')
require 'rubygems'
require 'rake'
require 'rake/clean'
require "bundler/gem_tasks"
require 'rake/packagetask'
require 'rdoc/task'
require 'aquarium/version'

# Use RSpec's files.
require 'rspec/core/rake_task'

# Some of the tasks are in separate files since they are also part of the website documentation
#load File.dirname(__FILE__) + '/rake_tasks/examples.rake'
# TODO: Replace rcov with simplecov and restore this feature.
#load File.dirname(__FILE__) + '/rake_tasks/verify_rcov.rake'

PKG_NAME = "aquarium"
PKG_VERSION   = Aquarium::VERSION::STRING
PKG_FILE_NAME = "#{PKG_NAME}-#{PKG_VERSION}"
PKG_FILES = FileList[
  '[A-Z]*',
  'lib/**/*.rb',
  'spec/**/*.rb',
  'examples/**/*.rb',
  'rake_tasks/**/*.rake'
]
FileUtils.touch(File.dirname(__FILE__) + '/previous_failures.txt')

IS_WINDOWS = (RUBY_VERSION == "1.8.7" ? PLATFORM : RUBY_PLATFORM) =~ /mswin/

WEBSITE_ROOT = "../doc/aquarium"

task :default => :spec

desc "Run all specs"
RSpec::Core::RakeTask.new do |t|
  t.rspec_opts = ['--color', '--format progress', '--profile']
end

Rake::PackageTask.new("aquarium", "#{Aquarium::VERSION::STRING}") do |p|
   p.need_zip = true
   p.need_tar = true
   p.package_files = `git ls-files`.split("\n")
 end

def egrep(pattern)
  Dir['**/*.rb'].each do |fn|
    count = 0
    open(fn) do |f|
      while line = f.gets
        count += 1
        if line =~ pattern
          puts "#{fn}:#{count}:#{line}"
        end
      end
    end
  end
end

desc "Look for TODO and FIXME tags in the code"
task :todo do
  egrep /(FIXME|TODO|TBD)/
end

task :clobber do
  rm_rf "#{WEBSITE_ROOT}/out"
  rm_rf "#{WEBSITE_ROOT}/webgen/out"
  rm_rf "#{WEBSITE_ROOT}/webgen/tmp"
  rm_rf 'translated_specs'
end

task :release => [:clobber, :verify_committed, :verify_user, :spec, :package_release]

task :package_release => [:website, :install, :package, :publish_packages, :tag, :publish_website, :publish_news]

# TODO!
desc "Verifies that there is no uncommitted code"
task :verify_committed do
  IO.popen('git status') do |io|
    io.each_line do |line|
      raise "\n!!! Do a git commit first !!!\n\n" if line =~ /^\s*M\s*/
    end
  end
end

desc "Creates a tag in git"
task :tag do
  `git tag #{Aquarium::VERSION::TAG}`
end

# desc "Creates a tag in svn (obsolete)"
# task :svntag do
#   from = `svn info #{File.dirname(__FILE__)}`.match(/URL: (.*)\/aquarium/n)[1]
#   to = from.gsub(/trunk/, "tags/#{Aquarium::VERSION::TAG}")
#   tag_cmd = "svn cp #{from} #{to} -m \"Tag release #{Aquarium::VERSION::FULL_VERSION}\""
#   raise "Can't tag to the same place: #{tag_cmd}" if to == from
#   puts "Creating tag in SVN"
#   `#{tag_cmd}`
#   raise "Tagging failed" unless $? == 0
# end

desc "Build the website, but do not publish it"
task :website => [:clobber, :rdoc, :webgen, :stage_website]

desc 'Generate HTML documentation for website'
task :webgen do
  puts "In #{WEBSITE_ROOT}, running 'rake webgen':"
  Dir.chdir "#{WEBSITE_ROOT}" do
    output = nil
    IO.popen('rake webgen 2>&1') do |io|
      output = io.read
    end
    if $? != 0
      puts "ERROR while running webgen: #{output}"
      raise "ERROR while running webgen"
    end
  end
end

desc 'Generate RDoc'
rd = Rake::RDocTask.new do |rdoc|
  rdoc.rdoc_dir = "#{WEBSITE_ROOT}/out/rdoc"
  rdoc.options << '--title' << 'Aquarium' << '--line-numbers' << '--main' << 'README'
  rdoc.rdoc_files.include('README', 'CHANGES', 'MIT_LICENSE', 'examples/**/*.rb', 'UPGRADE', 'lib/**/*.rb') # 'EXAMPLES.rd'
end

task :stage_website do
  # Hack so that cp_r works correctly:
  mv "#{WEBSITE_ROOT}/out/", "#{WEBSITE_ROOT}/out-tmp/"
  puts "cp_r #{WEBSITE_ROOT}/webgen/out, #{WEBSITE_ROOT}/out"
  cp_r "#{WEBSITE_ROOT}/webgen/out", "#{WEBSITE_ROOT}/out"
  mv "#{WEBSITE_ROOT}/out-tmp/rdoc", "#{WEBSITE_ROOT}/out"
  rmdir "#{WEBSITE_ROOT}/out-tmp/"

end

desc "Verify that the Aquarium specs run under JRuby and that JRuby can advise Java types. If this task fails, try running 'jruby -S rake' separately."
task :verify_jruby do
  puts "Verifying JRuby Support"
  Dir.chdir 'jruby' do
    rake = IS_WINDOWS ? "rake.cmd" : "rake"
    sh "jruby -S #{rake}"
  end
end


task :verify_user do
  raise "RUBYFORGE_USER environment variable not set!" unless ENV['RUBYFORGE_USER']
end

desc "Upload Website to RubyForge"
task :publish_website => [:verify_user, :website, :do_publish_website]

task :do_publish_website do
  unless Aquarium::VERSION::RELEASE_CANDIDATE
    # host = "aquarium-website@rubyforge.org"
    host = "#{ENV['RUBYFORGE_USER']}@rubyforge.org"
    publisher = Rake::SshDirPublisher.new(
      "#{host}",
      "/var/www/gforge-projects/#{PKG_NAME}",
      "#{WEBSITE_ROOT}/out"
    )
    publisher.upload
  else
    puts "** Not publishing packages to RubyForge - this is a prerelease"
  end
end

desc "Upload Website archive to RubyForge"
task :archive_website => [:verify_user, :website] do
  # host = "aquarium-website@rubyforge.org"
  host = "#{ENV['RUBYFORGE_USER']}@rubyforge.org"
  publisher = Rake::SshDirPublisher.new(
    "#{host}",
    "/var/www/gforge-projects/#{PKG_NAME}/#{Spec::VERSION::TAG}",
    "#{WEBSITE_ROOT}/out"
  )
  publisher.upload
end

desc "Publish gem+tgz+zip on RubyForge. You must make sure lib/version.rb is aligned with the CHANGELOG file"
task :publish_packages => [:verify_user, :package] do
  release_files = FileList[
    "pkg/#{PKG_FILE_NAME}.gem",
    "pkg/#{PKG_FILE_NAME}.tgz",
    "pkg/#{PKG_FILE_NAME}.zip"
  ]
  unless Aquarium::VERSION::RELEASE_CANDIDATE
    require 'meta_project'
    require 'rake/contrib/xforge'

    Rake::XForge::Release.new(MetaProject::Project::XForge::RubyForge.new(PKG_NAME)) do |xf|
      # Never hardcode user name and password in the Rakefile!
      xf.user_name = ENV['RUBYFORGE_USER']
      xf.files = release_files.to_a
      xf.release_name = "Aquarium #{PKG_VERSION}"
    end
  else
    puts "SINCE THIS IS A PRERELEASE, FILES ARE UPLOADED WITH SSH, NOT TO THE RUBYFORGE FILE SECTION"
    puts "YOU MUST TYPE THE PASSWORD #{release_files.length} TIMES..."

    # host = "aquarium-website@rubyforge.org"
    host = "#{ENV['RUBYFORGE_USER']}@rubyforge.org"
    remote_dir = "/var/www/gforge-projects/#{PKG_NAME}"

    publisher = Rake::SshFilePublisher.new(
      host,
      remote_dir,
      File.dirname(__FILE__),
      *release_files
    )
    publisher.upload

    puts "UPLADED THE FOLLOWING FILES:"
    release_files.each do |file|
      name = file.match(/pkg\/(.*)/)[1]
      puts "* http://aquarium.rubyforge.org/#{name}"
    end

    puts "They are not linked to anywhere, so don't forget to tell people!"
  end
end

desc "Publish news on RubyForge"
task :publish_news => [:verify_user] do
  unless Aquarium::VERSION::RELEASE_CANDIDATE
    require 'meta_project'
    require 'rake/contrib/xforge'
    Rake::XForge::NewsPublisher.new(MetaProject::Project::XForge::RubyForge.new(PKG_NAME)) do |news|
      # Never hardcode user name and password in the Rakefile!
      news.user_name = ENV['RUBYFORGE_USER']
    end
  else
    puts "** Not publishing news to RubyForge - this is a prerelease"
  end
end
