#!/opt/csw/bin/ruby -w

require 'rubygems'
require 'rubygems/format'

unless File.exists?(ARGV[0])
  $stderr.puts "Pass path to a valid .gem file as first argument.  You gave: #{ARGV[0]}"
  exit 1
end

begin
  spec = Gem::Format.from_file_by_path(File.expand_path(ARGV[0])).spec

  blurb = spec.description.gsub("\n", ' ').squeeze.lstrip

  puts <<"EOF"
NAME = #{spec.name}
VERSION = #{spec.version}
CATEGORIES = rbgems

DESCRIPTION = #{spec.summary}

define BLURB
  #{blurb.gsub(/(.{1,70})( +|$\n?)|(.{1,70})/, "\\1\\3")}
endef

EOF

  unless spec.dependencies.empty?
    spec.dependencies.each do |d|
      puts "RUNTIME_DEP_PKGS += CSWgem-#{d.name}"
    end
    puts
  end

  puts "ARCHALL = 1\n\n" if spec.extensions.size.eql?(0)

  puts "include gar/category.mk"
rescue Exception => e
  # we could be more selective, but this catches _everything_
  $stderr.puts "Rescued exception of type #{e.class}"
  $stderr.puts "Exception text: #{e.message}"
end
