require 'rbconfig'
require 'find'
require 'fileutils'
require 'optparse'

include Config

$ruby = CONFIG['ruby_install_name']

##
# Install a binary file. We patch in on the way through to
# insert a #! line. If this is a Unix install, we name
# the command (for example) 'rdoc' and let the shebang line
# handle running it. Under windows, we add a '.rb' extension
# and let file associations to their stuff
#

def installBIN(from, opfile)

  tmp_dir = nil
  [".", "/tmp", "c:/temp", $bindir].each{|t|
    stat = File.stat(t) rescue next
    if stat.directory? and stat.writable?
      tmp_dir = t
      break
    end
  }

  fail "Cannot find a temporary directory" unless tmp_dir
  tmp_file = File.join(tmp_dir, "_tmp")
    
    
  File.open(from) do |ip|
    File.open(tmp_file, "w") do |op|
      ruby = File.join($realbindir, $ruby)
#      op.puts "#!#{ruby}"
      op.write ip.read
    end
  end

  opfile += ".rb" if CONFIG["target_os"] =~ /mswin/i
  FileUtils::makedirs($bindir, {:verbose => true})
  FileUtils::install(tmp_file, File.join($bindir, opfile), 
                     {:mode => 0755, :verbose => true})
  FileUtils::safe_unlink(tmp_file)
end

# Main Program

opt = OptionParser.new
OPTS = {}
opt.summary_width = 23
opt.summary_indent = ''*1
opt.on('--bindir=VAL',
       'Directory to which the executable file is installed') \
      {|v| $bindir = v.to_s}
opt.on('--binname=VAL',
       'Name of the executable file (default name is "rdoc")') \
      {|v| $binname = v.to_s}
opt.on('--libdir=VAL', 
       'Directory to which the libraries are installed') \
       {|v| $libdir = v.to_s}
opt.on('--help', 'Show help message') {|v| OPTS[:help] = v}

opt.parse!(ARGV)

$bindir = File.expand_path($bindir) if $bindir
$binname ||= "rdoc"
$libdir = File.expand_path($libdir) if $libdir

install_opt = ""
install_opt = "--libdir=#{$libdir}" if $libdir

if $libdir
  $sitedir = $libdir
else
  $sitedir = CONFIG["sitelibdir"]
  unless $sitedir
    version = CONFIG["MAJOR"]+"."+CONFIG["MINOR"]
    $libdir = File.join(CONFIG["libdir"], "ruby", version)
    $sitedir = $:.find {|x| x =~ /site_ruby/}
    if !$sitedir
      $sitedir = File.join($libdir, "site_ruby")
    elsif $sitedir !~ Regexp.quote(version)
      $sitedir = File.join($sitedir, version)
    end
  end
end

$bindir ||= CONFIG["bindir"]
$realbindir = $bindir

bindir = CONFIG["bindir"]

rdoc_dest = File.join($sitedir, "rdoc")
rdoc_generator = File.join(rdoc_dest, "generator")
rdoc_parsers   = File.join(rdoc_dest, "parsers")
rdoc_ri        = File.join(rdoc_dest, "ri")

# help message
if ARGV[0] || OPTS[:help]
  print <<-HELP

  This ruby script installs libraries to \"#{$sitedir}\",
  and executables to \"#{$bindir}/#{$binname}\". (See \"rbconfig.rb\")

  If you want to install other directory, use following options.

  #{opt.help}

HELP
  exit
end

# make directories
[
  rdoc_dest,  
  rdoc_generator, 
  rdoc_parsers,
  rdoc_ri].each{|d|
  FileUtils::makedirs(d, {:verbose => true})
}

FileUtils::chmod(0755, rdoc_dest)



# The library files
files = %w{
 code_objects.rb
 generator.rb
 generator/*.rb
 options.rb
 parsers/parserfactory.rb  
 parsers/parse_*.rb  
 template.rb
 tokenstream.rb
 diagram.rb
 rdoc.rb
 dot.rb
 ri/*.rb
 ri.rb
 markup.rb
 stats.rb
}.collect {|f| Dir.glob(f)}.flatten

["chm", "html", "xml", "xhtml"].each{ |template|
  d = File.join(rdoc_generator, template)
  FileUtils::makedirs(d, {:verbose => true})
  files.concat Dir.glob("generator/#{template}/*.rb")
  files.concat Dir.glob("generator/#{template}/*.xsl")
}

files.each{ |aFile|
  dst = File.join(rdoc_dest, aFile)
  FileUtils::install(aFile, dst, {:mode => 0644, :verbose => true})
}

# and the executable

installBIN("rdoc", $binname)

# 'Markup' will eventually be a separate package, but
# for now we'll install it automatically 

Dir.chdir("markup") && system("#$ruby install.rb #{install_opt}")
