#!/usr/bin/env ruby

$version    = "1.0.0.beta"
$svn_server = "http://svn.narf-lib.org/svn/narf"

require 'pp'
require 'ftools'
require 'find'
require 'fileutils'
module FileUtils
  module Quiet
    include FileUtils
    @fileutils_output  = $stderr
    @fileutils_label   = ''
    FileUtils::OPT_TABLE.each do |name, opts|
      next unless opts.include?('verbose')
      module_eval(<<-EOS, __FILE__, __LINE__ + 1)
      def #{name}(*args)
        super(*fu_update_option(args, :verbose => false))
      end
      EOS
    end
    extend self
  end
end

include FileUtils::Quiet

require 'rbconfig';  include Config

module Kernel
  alias :rubyweb_system :system
  def system(*args)
    puts args.join(" ")
    rubyweb_system(*args)
  end
end

def temp_dir
  #(ENV["TEMP"] || "/tmp").gsub(/\\+/, "/")
  @temp_dir ||= File.join( Dir.pwd, "tmp" )
  mkdir @temp_dir unless File.exists? @temp_dir
  @temp_dir
end

def make_temp( path='' )
  File.join( temp_dir, path)
end

module Test
  module Unit
    class TestCase
	    @@subclasses = []
	    
	    def TestCase.inherited(sub)
        @@subclasses.push sub
	    end
	    
	    def TestCase.all_suite
        suite = Test::Unit::TestSuite.new
        @@subclasses.each{ |sub|
          suite << sub.suite # te
        }
        suite
	    end
    end
  end
end

task :default do
  Rake::application::display_tasks_and_comments
end

desc( "build all docs" )
task :doc => [:doc_html_multi, :doc_html_single ] do
end

desc( "build multi-page html" )
task :doc_html_multi do
  rm_rf 'dist/manual'
  mkdir 'dist/manual'
  cp 'doc/manual.css', 'dist/manual'
  system('xsltproc -stringparam base.dir dist/manual/ doc/xsl/manual-multi.xsl doc/manual.xml')
end

desc( "build single-page html" )
task :doc_html_single do
  rm 'dist/manual.html' if File::exists? 'dist/manual.html'
  system('xsltproc --output dist/manual.html doc/xsl/manual-single.xsl doc/manual.xml')
end

desc( "build pdf" )
task :doc_pdf do
  rm 'dist/manual.fo' if File::exists? 'dist/manual.fo'
  system('xsltproc --output dist/manual.fo doc/xsl/manual-pdf.xsl doc/manual.xml')
end

#Target.new( "upload_doc", "upload doc" ) {
#  Target.run( "rdoc" )
#  `scp -r doc/rdoc/* patsplat@ssh.narf-lib.org:~/narf-lib.org/doc`
#}

#Target.new( "rdoc", "build rdoc" ) {
#  begin
#    require 'rdoc/rdoc'
#    
#    rdoc = RDoc::RDoc.new
#    rdoc.document( [  
#                     # set the output directory
#                     "-o", 
#                    "doc/rdoc/",
#                    
#                    # template
#                    "-1",
# 
#                    # set the main page
#                    "--main",
#                    "README",
#                    
#                    # list the files to be excluded
#                    "--exclude",
#                    /htmltools|htmlparser|unit|writableio|tagparser|strscanparser|web\/action|assertinclude|buffer|formreader|forms|runner|simpledispatcher|traceoutput|linker|page|lib\/web\/sapi/,
#                    # list the files / dirs to be parsed for documentation
#                    "README",
#                    "examples/examples.rdoc",
#                    "lib/web.rb",
#                    "lib/web",
#                    "doc/apache_cgi.txt",
#                    "doc/windows_cgi.txt",
#                    "doc/fastcgi.txt",
#                    "doc/mod_ruby.txt",
#                    "doc/webrick.txt",
#                    "doc/manual.txt",
#		  ] )
#  rescue LoadError => error
#puts "Building the rdocs will require 'rdoc/rdoc'"
#puts "visit http://rdoc.sourceforge.net/ to obtain this library"
#  end
#}

desc "run tests for Web module"
task :test do
  Dir.mkdir( 'tmp' ) unless File.exists? 'tmp'
  require 'test/unit'
  require 'test/unit/ui/console/testrunner'
  
  $:.replace(['lib'].concat($:))
  
  require 'web'
  require 'web/testing'
  
  if ENV['TEST']
    require "test/web/#{ENV['TEST']}"
  else
    Dir["test/web/*.rb"].sort.each { |test|
      require test
    }
  end

  Test::Unit::UI::Console::TestRunner.new( Test::Unit::TestCase.all_suite ).start
  rm_rf "tmp"
end

desc "run wiki tests"
task :testwiki do
  require 'test/unit'
  require 'test/unit/ui/console/testrunner'
  
  $:.replace( ['./lib/'].concat($:) ) 
  
  require 'web/testing'
  require 'web/wiki'
  
  def setup_wiki
    rm_rf( Web::Wiki::store_dir )
    Web::Wiki::wipe
  end
  
  alias :teardown_wiki :setup_wiki
  
  Dir.mkdir "tmp" unless File.exists? "tmp"
  Dir.mkdir "tmp/test.pages" unless File.exists? "tmp/test.pages"
  Dir.mkdir "tmp/tarpit" unless File.exists? "tmp/tarpit"
  
  Web::Wiki::set_pref(:store_dir  => make_temp("test.pages/"),
                      :store_url  => "../test.pages/",
                      :tarpit_dir => make_temp("tarpit/"),
                      :vandals    => "vandals.test.txt",
                      :baseurl    => "wiki.rb" )
  
  Web::docroot = File.join(Dir.pwd,"test/wikitestroot")
  
  Dir["test/wiki/*.rb"].each { |test|
    require test
  }
  
  # buffered test runner is a custom made test runner
  # that lives in the test dir
  begin
    Test::Unit::UI::Console::TestRunner.new(Test::Unit::TestCase.all_suite).start
  rescue Exception => err
    puts err.to_s
    puts err.backtrace
  end
  rm_rf 'pages'
end

desc "test installation, requires param URL=http://localhost/script_calling_Web::info.rb"
task :testinstall do
  $: << Dir.pwd + "/lib"
  require 'webunit'
  
  # I don't like how webunit is appending a '/'
  # at the end of my urls.
  module WebUnit
    class TestCase
      def initialize( method, name=self.class.name )
        case USING_FRAMEWORK
        when 'Test::Unit'
          super(method)
        when 'RubyUnit'
          super
        else
          super
          # raise??
        end
        @urlbase = ENV['URL'] ? ENV['URL'] : 'http://localhost/'
        @urlbase = orthop_url( @urlbase )
        #@urlbase << '/' unless @urlbase =~ %r!/$!
        $stderr.puts "URLBASE is #{@urlbase}" if $DEBUG
      end
    end
  end
  
  ENV['URLBASE'] = ARGV[1] || ENV['URLBASE'] || "http://www.hexane.org/webtest/"
  require 'webunit/runtest'

  Dir.chdir( "test/installation" )
  WebUnit.runtest(Dir["test*.rb"])
end

desc "test examples"
task :testexamples do
  require 'test/unit'
  require 'test/unit/ui/console/testrunner'

  $:.replace(['./lib/'].concat($:)) 

  require 'web'
  require 'web/wiki'
  require 'web/testing'

  Web.set_docroot File.join(Dir.pwd,"examples", "htdocs")

  Dir["examples/test/*.rb"].each { |test|
    require test
  }

  # buffered test runner is a custom made test runner
  # that lives in the test dir
  Test::Unit::UI::Console::TestRunner.new(Test::Unit::TestCase.all_suite ).start
end

desc "remove compiled files"
task :clean do
  ["bin/ruby-web.exe",
   "bin/ruby-web",
   "dist" ].each do |f|
    rm_rf f
  end
end

desc "compile interpreter"
task :compile do
  Dir.mkdir "bin" unless File.exists? "bin"
  rm 'bin/ruby-web'     if File.exists?('bin/ruby-web')
  rm 'bin/ruby-web.exe' if File.exists?('bin/ruby-web.exe')
    
    require 'rbconfig'
    
    if (Config::CONFIG['sitearch'] =~ /windows|msvcrt/)
      cp 'sapi/win/ruby-web.exe', 'bin/ruby-web.exe'
    else
      c          = Config::CONFIG
      libdir     = c['libdir']
      archdir    = c['archdir']
      ld         = c['CC']
      ldflags    = c['LDFLAGS']
      xldflags   = c["XLDFLAGS"]
      xldflags.gsub!(/-L\./, "")
      xldflags  += " #{c['LIBPATHFLAG'] % libdir}"
      librubyarg = c["LIBRUBYARG"]
      if c["RUBY_SHARED"]
        librubyarg.gsub!(/-L\./, "")
      end
      
      libs = c["LIBS"] # + " -lruby"

      unless librubyarg =~ /ruby/
        librubyarg += " -lruby"
      end
      
      #(cmd = "gcc sapi/ruby-web.c -v -I#{archdir} -L#{libdir} #{c['libs']} #{librubyarg} -o bin/ruby-web")
      
      cmd = [ ld, ldflags, xldflags, "-I#{archdir}", "sapi/ruby-web.c", librubyarg, libs, "-o bin/ruby-web" ].join(" ")
      system(cmd)
    end
end

desc "make distribution files"
task :dist do
  rm_rf "dist"
  mkdir "dist"
  
  Task[:tgz].invoke
  Task[:macpkg].invoke
  Task[:winpkg].invoke

  puts "finished dist"
end

desc "make basic tar.gz pkg"
task :tgz => [:compile] do
  pkg    = "ruby-web_#{$version}.tar.gz"
  pkgdir = "ruby-web-#{$version}"
  svn    = "svn"
  
  cd 'dist'
  rm_rf pkg
  rm_rf pkgdir
  system("#{svn} export #{$svn_server}/trunk #{pkgdir}" )
  cd pkgdir
  system("rake doc")
  cd ".."
  system("tar cvzf #{pkg} #{pkgdir}")
  rm_rf pkgdir
  cd ".."
end

desc "make Mac OS X pkg"
task :macpkg => [:compile] do
  pkg     = "ruby-web_#{$version}-powerpc-darwin"
  pkginfo = File.expand_path("sapi/macpkg/Info.plist")
  pkgdesc = File.expand_path("sapi/macpkg/Description.plist")
  pkgrsrc = File.expand_path("sapi/macpkg/Resources")
  pkgroot = File.expand_path("dist/macpkg")
  pkgbin  = "#{pkgroot}/usr/bin"
  pkglib  = "#{pkgroot}/usr/lib/ruby/site_ruby/1.8/"
  
  rm_rf pkgroot
  rm_rf "dist/#{pkg}.dmg"
    
  if CONFIG["sitearch"] =~ /darwin/
    mkdir_p pkgbin
    mkdir_p pkglib
    mkdir_p "dist/#{pkg}"
    cp   "bin/ruby-web", pkgbin
    cp_r Dir["lib/*"], pkglib

    system "/Developer/Tools/packagemaker -build -ds -p dist/#{pkg}/#{pkg}.pkg -f #{pkgroot} -i #{pkginfo} -d #{pkgdesc} -r #{pkgrsrc}"
    system "hdiutil create -srcfolder dist/#{pkg} dist/#{pkg}.dmg"
    
    rm_rf( "dist/#{pkg}" )
    rm_rf pkgroot
  end

  #hdiutil internet-enable -yes|-no|-query <pathToDMG>
end

desc "make Win installer"
task :winpkg => [:compile] do
  pkg     = "ruby-web_#{$version}-windows"
  pkgroot = File.expand_path("dist/winpkg")
  pkgbin  = "#{pkgroot}/bin"
  pkglib  = "#{pkgroot}/lib/ruby/site_ruby/1.8/"

  rm_rf pkgroot
  rm_rf "dist/#{pkg}.exe"

  if CONFIG["sitearch"] =~ /msvcrt/
    mkdir_p pkgbin
    mkdir_p pkglib
    cp   "bin/ruby-web.exe", pkgbin
    cp_r Dir["lib/*"], pkglib  

    cp "sapi/win/apache1.ini", pkgroot
    cp "sapi/win/apache2.ini", pkgroot
    
    cd pkgroot
    
    system "makensis /NOCD /DVERSION=#{$version} /DOUTFILE=../#{pkg}.exe ../../sapi/win/ruby-web.nsi"
    
    cd "../.."
    rm_rf pkgroot
  end
end
