#!/usr/bin/ruby
Copyright = %$Copyleft: (c) 2001 Nakada.Nobuyoshi <nobu.nokada@softhome.net> $.freeze
RCSID = %w$Id: install.rb,v 0.6 2001/04/08 09:13:46 nobu Exp $[1..-1].each {|s| s.freeze}.freeze
Version = RCSID[1].split('.').collect {|s| s.to_i}.extend(Comparable).freeze
Release = RCSID[2]

srcdir = File.dirname(__FILE__)
$:.unshift(srcdir)
require 'optparse'
require 'rbconfig'
require 'ftools'

ARGV.options {|q|
  @exec = true
  @verbose = true
  @more = true
  q.banner = "Usage: ruby #{q.program_name} [OPTIONS] [more]\n"
  q.summary_width = 44
  q.on('--site-install', '--default', 'install to site_ruby') {@dest = nil}
  q.on('--more-install', 'install some more files') {|@more|}
  q.on('-l', '--less', 'not install optional files') {@more = false}
  q.on('-C', '--destdir=DIR', '--destination-directory', String, 'install to DIR') {|@dest|}
  q.on('-q', '--no-verbose', '--[no-]quiet', 'run verbosely/quietly') {|@verbose|}
  q.on('-n', '--no-install', '--show-only', FalseClass, 'show settings and exit') {|@exec|}
  q.order! do |nonopt|
    begin
      q.parse("--#{nonopt}")
    rescue OptionParser::InvalidOption
      raise OptionParser::InvalidArgument, nonopt if @dest
      @dest = nonopt
    end
  end
} or (puts ARGV.options; exit 1)

if @exec
  def makedirs(d)
    File.makedirs(d, @verbose)
  end
  def install(src, dest, mode = 0644)
    File.install(src, dest, mode, @verbose)
  end
else
  def makedirs(d)
    puts("install -d #{d}")
  end
  def install(src, dest, mode = 0644)
    printf("install -m %o %s %s\n", mode, src, dest)
  end
end

@dest ||= Config::CONFIG['sitedir']
if srcdir == '.'
  srcdir = ''
else
  srcdir.sub!(/[^\/]\z/, '\&/')
end
files = ["#{srcdir}optparse.rb"]
files.concat(Dir.glob("#{srcdir}optparse/**/*.rb")) if @more

dirs = {}
files.each do |f|
  dest = File.join(@dest, f[srcdir.length..-1])
  dirs[d = File.dirname(dest)] ||= (makedirs(d); true)
  install(f, dest)
end
