#! /usr/local/bin/ruby

# sample ~/.gemmirrorc:
#--- 
#- 
#  from: http://gems.rubyforge.org/
#  to: /Users/glasser/MyGEMS/gems.rubyforge.org

require 'yaml'
require 'rubygems'
require 'open-uri'

config_file = File.join(Gem.user_home, '.gemmirrorrc')

raise "Config file #{config_file} not found" unless File.exist?(config_file)

mirrors = YAML.load_file(config_file)

mirrors.each do |mir|
  raise "mirror missing 'from' field" unless mir.has_key?('from')
  raise "mirror missing 'to' field" unless mir.has_key?('to')
  
  get_from = mir['from']
  save_to = mir['to']

  raise "Directory not found: #{save_to}" unless File.exist?(save_to)
  raise "Not a directory: #{save_to}" unless File.directory?(save_to)

  gems_dir = save_to + "/gems"
  if File.exist?(gems_dir)
    raise "Not a directory: #{gems_dir}" unless File.directory?(gems_dir)
  else
    Dir.mkdir(gems_dir)
  end

  sourceindex_text = ''

  open(get_from + "/yaml", "r") do |y|
    sourceindex_text = y.read
    open(save_to + "/yaml", "wb") do |out|
      out.write(sourceindex_text)
    end
  end

  sourceindex = YAML.load(sourceindex_text)

  sourceindex.each do |fullname, gem|
    gem_file = fullname + '.gem'
    unless File.exists?(gems_dir + "/" + gem_file) 
      puts "fetching: " + gem_file
    
      begin
        open(get_from + "/gems/" + gem_file, "r") do |g|
          contents = g.read
          open(gems_dir + "/" + gem_file, "wb") do |out|
            out.write(contents)
          end
        end
      rescue
        old_gf = gem_file
        gem_file = gem_file.downcase
        retry if old_gf != gem_file
        puts $!
      end
    end
  end
end
