#!/usr/bin/ruby
# -*- ruby -*-

$LOAD_PATH.push(File.expand_path(File.dirname(__FILE__) + "/../lib"))

require 'gem2rpm'
require 'fileutils'
require 'tmpdir'
require 'open-uri'
require 'uri'

options = begin
  Gem2Rpm::Configuration.instance.options
rescue Gem2Rpm::Configuration::InvalidOption => e
  Gem2Rpm.show_message(e)
  exit(1)
end
if options[:templates]
  Gem2Rpm.show_templates
  exit(0)
end
if options[:version]
  Gem2Rpm.show_version
  exit(0)
end

rest = options[:args]

template = begin
  Gem2Rpm::Template.find options[:template_file], :gem_file => rest[0]
rescue Gem2Rpm::Template::TemplateError => e
  $stderr.puts e
  exit(1)
end

if options[:print_template_file]
  puts template.read
  exit 0
end

if rest.size != 1
  Gem2Rpm.show_message('Missing GEMFILE')
  exit(1)
end
gemfile = rest[0]
out_dir = options[:directory]
unless File.directory?(out_dir)
  Gem2Rpm.show_message("No such directory #{out_dir}")
  exit(1)
end

if options[:fetch]
  gem_uri = ''
  begin
    URI("https://rubygems.org/api/v1/gems/#{gemfile}.json").open do |f|
      gem_uri = f.read.match(/"gem_uri":\s*"(.*?)",/m)[1]
      gemfile = URI.parse(gem_uri).path.split('/').last
      gemfile = File.join(out_dir, gemfile)
      open(gemfile, 'w') do |gf|
        gf.write(URI(gem_uri).open.read)
      end
    end
  rescue OpenURI::HTTPError => e
    Gem2Rpm.show_message("Gem fetch failed with error: #{e.message}")
    exit(1)
  end
end

unless File.exist?(gemfile)
  Gem2Rpm.show_message("Invalid GEMFILE #{gemfile}")
  exit(1)
end

if options[:deps]
  Gem2Rpm.print_dependencies(gemfile)
  exit 0
end

output_spec = StringIO.new
Gem2Rpm.convert(gemfile, template, output_spec, options[:nongem], options[:local], options[:doc_subpackage])

# Save or print a specfile.
if options[:output_file]
  File.open(options[:output_file], "w") do |f|
    f.puts(output_spec.string)
  end
else
  puts output_spec.string unless options[:srpm]
end

# Create a SRPM.
if options[:srpm]
  gemname = Gem::Package.new(gemfile).spec.name
  Dir.mktmpdir "gem2rpm-#{gemname}-" do |srpmdir|
    specfile = File.join(srpmdir, "rubygem-#{gemname}.spec")

    File.open(specfile, "w") do |f|
      f.puts(output_spec.string)
    end

    FileUtils.copy(gemfile, srpmdir)

    command =
      "rpmbuild -bs --nodeps " +
      "--define '_sourcedir #{srpmdir}' " +
      "--define '_srcrpmdir #{out_dir}' " +
      specfile

    unless system(command)
      Gem2Rpm.show_message("Command failed: #{command}")
      exit(1)
    end
  end
end
