#!/usr/bin/env ruby

require 'rubygems'
require 'optparse'

EXT = %w( .rb .rbw .so .dll )

options = OptionParser.new
options.banner = "gemwhich -- Find the location of a library module."
options.separator("")
options.separator("Usage: gemwhich [options] libname...")
options.on_tail('-v', '--verbose',
  "Enable verbose output"
  ) do |value|
  $verbose = value
end
options.on_tail('-h', '--help',
  "Display this help message"
  ) do |value|
  puts options
  exit
end
ARGV << '-h' if ARGV.empty?

begin
  options.parse!(ARGV)
rescue OptionParser::InvalidOption => ex
  puts "Error: #{ex.message}"
  exit
end

def find_path(package_name, dirs)
  dirs.each do |dir|
    EXT.each do |ext|
      full_path = File.join(dir, "#{package_name}#{ext}")
      if File.exist?(full_path)
	return full_path
      end
    end
  end
  nil
end

searcher = Gem::GemPathSearcher.new
ARGV.each do |arg|
  dirs = $LOAD_PATH
  spec = searcher.find(arg)
  if spec
    dirs =
      spec.require_paths.collect { |d|
      File.join(spec.full_gem_path,d)
    } + $LOAD_PATH
    puts "(checking gem #{spec.full_name} for #{arg})" if $verbose
  end
  path = find_path(arg, dirs)
  if path
    puts path
  else
    puts "Can't find #{arg}"
  end
end
