#!/usr/bin/ruby
#
# Copyright © 2011, Lucas Nussbaum <lucas@debian.org>
#
# 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 3 of the License, 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, see <http://www.gnu.org/licenses/>.

require 'fileutils'
require 'gem2deb'
require 'gem2deb/gem2tgz'
require 'gem2deb/dh_make_ruby'
require 'optparse'

$only_tarball = false
$only_source_dir = false
$only_debian_source = false
$check_build_deps = true
$git = nil
$purge = false
$generated = []
dh_make_ruby_options = {}

optparse = OptionParser.new do |opts|
  opts.banner = "Usage: gem2deb [OPTIONS] GEMNAME|GEMFILE"
  opts.separator "Options:"

  opts.on('-h', '--help', 'show gem2deb help') do
    puts opts
    exit
  end

  opts.on('-v', '--version', 'show gem2deb version') do
    puts "gem2deb version #{Gem2Deb::VERSION}"
    exit
  end

  opts.on('-t', '--only-tarball', 'stop after creating the tar.gz archive') do
    $only_tarball = true
  end

  opts.on('-s', '--only-source-dir', 'stop after preparing the Debian source package') do
    $only_source_dir = true
  end

  opts.on('-S', '--only-debian-source', 'only build source package ; no binary packages') do
    $only_debian_source = true
  end

  opts.on('-d', '--no-check-builddeps', 'do not check build dependencies') do
    $check_build_deps = false
  end

  opts.on('-p', '--package PACKAGE', 'specify package name (default: ruby-*)') do |package_name|
    dh_make_ruby_options[:source_package_name] = package_name
  end

  opts.on('-g', '--git', 'Import resulting package to a git repository under the current directory') do |dir|
    $git = File.expand_path('.')
  end

  opts.on('--purge', 'Purge all non-preexisting files produced') do
    $purge = true
  end

  opts.on('', '--ruby-versions VERSIONS', 'ruby versions to use (default: all)') do |versions|
    dh_make_ruby_options[:ruby_versions] = versions
  end

  dh_make_ruby_options[:do_wnpp_check] = true
  opts.on('', '--no-wnpp-check', 'prevent dh-make-ruby to check for ITP bugs') do
    dh_make_ruby_options[:do_wnpp_check] = false
  end

  opts.on('-o', '--offline', 'Do not access the internet for anything') do
    dh_make_ruby_options[:do_wnpp_check] = false
  end

end
optparse.parse!

if ARGV.length != 1
  puts optparse
  exit(1)
end

gemfile = ARGV[0]
# Download gem if not available locally
if not File::exists?(gemfile) and gemfile !~ /.gem$/
  puts "#{gemfile} doesn't seem to exist. Let's try to download it with 'gem fetch #{ARGV[0]}'"

  tmpdir = Dir.mktmpdir
  begin
    Dir.chdir(tmpdir) do
      if gemfile =~ /^rails-assets/
        run("gem", "fetch", "--source", "https://rails-assets.org", gemfile)
      else
        run("gem", "fetch", gemfile)
      end
      gemfile = Dir.glob('*.gem').first
      unless gemfile
        # no .gem means that `gem fetch` failed (but still exited with 0)
        raise RuntimeError.new("Failed to download .gem file")
      end
    end
    FileUtils.mv(File.join(tmpdir, gemfile), '.')
  rescue RuntimeError => ex
    puts ex.message
    exit(1)
  ensure
    FileUtils.rm_rf(tmpdir)
  end
  $generated << gemfile
end

gemfiledir = File.dirname(gemfile)
gemfile = File.basename(gemfile)
Dir.chdir(gemfiledir)

puts "-- Creating source tarball from #{gemfile} ..."
tarball = Gem2Deb::Gem2Tgz.convert!(gemfile)
$generated << tarball
puts "-- Successfully created #{tarball}"

exit(0) if $only_tarball

puts
puts "-- Creating Debian source package from #{tarball} ..."
dmr = Gem2Deb::DhMakeRuby::new(tarball, dh_make_ruby_options)
source = dmr.build
puts "-- Generated Debian source tree in #{dmr.source_dirname}"

exit(0) if  $only_source_dir

puts
puts "-- Building Debian package ..."
ENV['DEB_BUILD_OPTIONS'] =
  [ENV['DEB_BUILD_OPTIONS'], 'dh_ruby_interactive'].compact.join(' ')
dmr.buildpackage($only_debian_source, $check_build_deps)
puts "-- Debian package successfully built!"

pkg = Dir.chdir(source) { `dpkg-parsechangelog -SSource`.strip }
version = Dir.chdir(source) { `dpkg-parsechangelog -SVersion`.strip }

if $git
  Dir.chdir(source) do
    dsc = "../#{pkg}_#{version}.dsc"
    cmd = ['gbp', 'import-dsc', '--pristine-tar', dsc, File.join($git, pkg)]
    if system(*cmd)
      puts "-- Package imported to git repository!"
    else
      exit(1)
    end
  end
end

if $purge
  Dir.chdir(source) do
    changes = Dir["../#{pkg}_#{version}_*.changes"]
    `dcmd ls -1 #{changes.join(" ")}`.split.each do |f|
      $generated << File.join(source, f)
    end
  end
  $generated << source
  $generated.map! do |f|
    File.expand_path(f)
  end
  run('rm', '-rf', *$generated)
  puts('-- Intermediate files removed')
end

__END__
=head1 NAME

gem2deb - converts Rubygems' .gem file into Debian package

=head1 SYNOPSIS

B<gem2deb> [I<OPTIONS>] I<GEMNAME> (to download the gem with I<gem fetch>)

B<gem2deb> [I<OPTIONS>] I<GEMFILE> (to use a local .gem file)

=head1 DESCRIPTION

B<gem2deb> converts the gem into a Debian source package, and then will attempt
to build it. The process is made of several steps.

First, B<gem2deb> converts the gem file to a tar.gz archive containing a
metadata.yml file with the Gem specification. This is equivalent to what
B<gem2tgz> does.

Then, B<gem2deb> unpacks the tar.gz archive and prepares a Debian source
package, guess many of the defaults from the files included in the archive, or
the Gem specification. This is equivalent to what B<dh-make-ruby> does.
B<gem2deb> cannot determine all parameters for obvious reasons. It is recommended
to search for the "FIXME" string in the I<debian/> directory.
The generated Debian source package uses B<dh_ruby> to build the package.

Finally, B<gem2deb> tries to build the source and binary packages using
B<dpkg-buildpackage>.

=head1 OPTIONS

=over

=item B<-t>, B<--only-tarball>

Stop after creating the tar.gz archive.

=item B<-s>, B<--only-source-dir>

Stop after preparing the Debian source package directory (do not attempt to
build the package).

=item B<-S>, B<--only-debian-source>

Only build a Debian source package (do not build binary packages).

=item B<-d>, B<--no-check-builddeps>

Do not check build dependencies when building the package. Equivalent to the
options with the same in B<dpkg-buildpackage(1)>.

=item B<-p PACKAGE>, B<--package PACKAGE>

Specify package name (default: ruby-*).
Passed to dh-make-ruby. See B<dh-make-ruby(1)>.

=item B<-g>, B<--git>

Import the resulting source package, if any, to a git repository under the
current directory. The git repository will be named after the source package
(i.e. it is influenced by B<--package>).

Note that B<--only-tarball> or B<--only-source-dir> will prevent this, since
they make B<gem2deb> stop early.

The import uses B<gbp import-dsc --pristine-tar> (see B<gbp-import-dsc(1)>),
and thus I<git-buildpackage> and B<pristine-tar> need to be installed for this
to work.

=item B<--purge>

After building the package, remove all files files that were produced by
gem2deb. This includes source tarballs, Debian package artifacts (.dsc, .deb,
.changes etc), and even the source directory. This is useful for example when
used in conjunction with B<--git>.

=item B<--ruby-versions VERSIONS>

Ruby versions to build the package for (default: all).
Passed to dh-make-ruby. See B<dh-make-ruby(1)>.

=item B<--no-wnpp-check>

Prevents B<dh-make-ruby> to check wnpp reports to get the number of a possible
ITP (intend to package) bug report. By default, B<dh-make-ruby> does check these
reports, which requires an Internet access.

=item B<-o>, B<--offline>

Prevents B<dh-make-ruby> from accessing the internet at all.

=item B<-h>, B<--help>

Displays B<gem2deb> usage information.

=item B<-v>, B<--version>

Displays B<gem2deb> version information.

=back

=head1 HOW THE .GEM -> .TGZ CONVERSION WORKS

A gem named I<mygem-0.1.0.gem> is converted in a tarball with
(approximately) the following steps:

  mkdir mygem-0.1.0
  cd mygem-0.1.0
  tar xfm /absolute/path/to/mygem-0.1.0.gem
  tar xzfm data.tar.gz
  zcat metadata.gz > metadata.yml
  rm -f data.tar.gz metadata.gz
  cd ..
  tar czf mygem-0.1.0.tar.gz mygem-0.1.0
  rm -rf mygem-0.1.0

The generated tarball has the following properties:

=over

=item Files

It contains all the files the gem contains.

=item Metadata

It contains the gem metadata in a file named ``metadata.yml`` inside
the I<mygem-0.1.0> directory.

=back

=head1 SEE ALSO

L<B<dh_ruby>>(1)

=head1 COPYRIGHT AND AUTHORS

Copyright (c) 2011, Lucas Nussbaum <lucas@debian.org>

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 3 of the License, 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, see <http://www.gnu.org/licenses/>.
