#!/usr/bin/env ruby

# install.rb   May 2002
#
# Copyright (c) 2002 by Matthias Veit <matthias_veit@yahoo.de>
# 
# This program is free software; you can redistribute it and/or modify
# it under the terms of the GNU General Public License as published by
# the Free Software Foundation; either version 2, or (at your option) 
# any later version.
#  
# This program is distributed in the hope that it will be useful,
# but WITHOUT ANY WARRANTY; without even the implied warranty of 
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the  
# GNU General Public License for more details.
#  
# You should have received a copy of the GNU General Public License
# along with this program; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  
# 02111-1307, USA.

=begin

Ruby Object Teams (ROT)

= Introduction

This script installs ROT into the Ruby site-local library directory.

= Usage

       ruby install.rb
              --install_dir <dir> - the directory to install
              --help              - get help

=end

require 'getoptlong'
require 'ftools'
require 'find'

SOURCE_DIR = 'objectteam'
LIBDIR = 'objectteam'

def parse_args
  install_dir = nil
  help = false
  g = GetoptLong.new(
        ['--install-dir', '-i', GetoptLong::REQUIRED_ARGUMENT],
        ['--help', '-h', GetoptLong::NO_ARGUMENT]
  )
  g.each { |opt, arg|
    if (opt == '--install-dir')
      install_dir = arg
    elsif (opt == '--help')
      help = true
    else
      help = true
    end
  }
  return [install_dir, help]
end

def install_dir
  libdir = nil
  begin
    require 'rbconfig'
    libdir = Config::CONFIG['sitedir'] + "/"+Config::CONFIG['MAJOR']+"."+Config::CONFIG['MINOR']
  rescue ScriptError
    $LOAD_PATH.each do |l|
        if l =~ /site_ruby/ && l =~ /\d$/ && l !~ /#{PLATFORM}/
          libdir = l
          break
        end
    end
    STDERR.puts "Can't find required file `rbconfig.rb'."
    STDERR.puts "The `objectteam' files need to be installed manually in #{libdir}."
  end
  return libdir
end

def install(source, destination)
  begin
    File.install(source, destination, 0644, true) 
  rescue Errno::EACCES
    puts "Access not permitted! #{$!}"
  rescue
    puts "Error: #{$!}"
  end
end

def usage()
  puts "usage: #{$0}\n"+
       "       --install_dir <dir> - the directory to install (default=#{install_dir()})\n"+
       "       --help              - this usage\n"
end

def main()
  instdir, help = parse_args()
  if (help)
    #some informative description
    usage
  else
    #install directory
    instdir = (instdir or install_dir())
    #make sink directory
    File.makedirs(File.join(instdir, LIBDIR))
    #all ruby files beneath SOURCE_DIR
    Find.find(SOURCE_DIR) { |f|
      install(f, File.join(instdir, f)) if f =~ /.rb$/
    }
    #install includer
    install("objectteam.rb", File.join(instdir, "objectteam.rb"))
  end
end
  
main()
