require 'rubygems'
require 'rake/clean'
require 'fileutils'

task :default => [:update_docs, :build, :clean]

CLEAN.include("**/.DS_Store")

desc "Build the website from source"
task :build do
  puts "Building website from static source"
  result = system("middleman build --clean")
  if result
    puts "Successfully generated the site, please commit your changes"
  else
    puts "An error was encountered when generating the site"
  end
end

desc "Update the latest docs from the Apache Mesos codebase"
task :update_docs do
  puts "Updating latest documentation from the Apache Mesos codebase"

  docs_dir = File.join(File.dirname(__FILE__), "source/documentation")

  puts "Updating docs to the latest version"
  FileUtils.mkdir_p("source/documentation/latest/")
  FileUtils.rm_f(Dir.glob("source/documentation/latest/*.md"))
  FileUtils.cp_r(Dir.glob("../docs/*.md"), File.expand_path("source/documentation/latest/"))
  puts "Parse documentation files to removing md extension in any links"
  Dir.chdir("#{docs_dir}/latest/") {
    Dir.glob('*.md').each { |doc|
      puts "working on: #{doc}"
      IO.write(doc, File.open(doc) { |f|
        f.read
          .gsub(/\(([^(\/]+)\.md(\#.+?)?\)/, '(/documentation/latest/\1/\2)')
          .gsub(/\(images\/(.*)\)/, '(/assets/img/documentation/\1)')
      })
    }
  }
  puts "Moving documentation index to its own 'latest' directory"
  FileUtils.mv("source/documentation/latest/home.md", "source/documentation/latest.html.md")
  puts "Documentation updated"

  # Copy the images from the docs
  FileUtils.mkdir_p("source/assets/img/documentation/")
  FileUtils.rm_f(Dir.glob("source/assets/img/documentation/*"))
  FileUtils.cp_r(Dir.glob("../docs/images/*"), File.expand_path("source/assets/img/documentation/"))
end

desc "Generate javadoc from the Java source files in the codebase"
task :javadoc do
  # TODO: add version to the path. Uses 'current' for now.
  system("javadoc -d publish/api/latest/java -sourcepath ../src/java/src org.apache.mesos")
end

desc "Generate doxygen from the C++ source files in the codebase"
task :doxygen do
  system("pushd .. && doxygen && popd && rsync -avz ../docs/html/* publish/api/latest/c++")
end

desc "Run the site in development mode. Preview available at http://localhost:4567/"
task :dev do
  system("middleman server")
end
