#!/usr/bin/perl -w

use strict;
use warnings;
use Carp;
use Getopt::Long;
use RPM::Source::Editor;
Getopt::Long::Configure ("bundling","auto_abbrev");

my ($try_srpm_first, $nodeps,$help);
my $verbose=1;
my $outputdir;

sub usage () {
    my ($self)=@_;
    print "$0 [options] /path/to/spec1 ... /path/to/specN
general options:
	-h, --help
	-v, --verbose (can be specified multiple times)
	
output options:
	--outdir /path/to/output_dir
processing options:
	--nodeps ignored for compatibility with rpmbuild.
	-b|-s|-bs try to write src.rpm file first, then fallback to hashertar.
";
}


my $result = GetOptions (
		      'b|s|bs'   => \$try_srpm_first,
		      "nodeps"   => \$nodeps,
		      "outdir=s"   => \$outputdir,
		      "v|verbose+"  => \$verbose,
		      "q|quiet"  => sub {$verbose=0},
		      "h|help"  => \$help,
    );

if (not @ARGV or $help) {
    usage();
    exit (1);
}

foreach my $inspec (@ARGV) {
    unless (-e $inspec) {
	die "spec file $inspec not found.\n";
    }
    my $spec=RPM::Source::Editor->new(
	SPECFILE=> $inspec, 
	OUTPUTDIR=> $outputdir, 
	VERBOSE=> $verbose,
	'-fallback_hasher_tar' => 1,
	'-readonly' => 1,
	);
    # TODO: merge this hack.
    $spec->{SOURCEDIR}=$spec->macros()->macro_subst('%{_sourcedir}');
    $spec->{OUTPUTDIR}=$spec->macros()->macro_subst('%{_srcrpmdir}') unless $outputdir;

    if ($try_srpm_first) {
	$spec->write_rpm($inspec);
    } else {
	$spec->write_hasher_tar();
    }
}


__END__

=head1	NAME

hashertarbuild - A tool to create source tarballs for hasher.

=head1	DESCRIPTION

hashertarbuild is a tool to create  rpm-based source tarballs for hasher.
Sometimes rpmbuild -bs --nodeps <spec> does not work due to a macros abcent.
Use hashertarbuild <spec> to create source tarball ready for hasher.
Use hashertarbuild -bs <spec> to try creating source rpm first then to fallback
to hasher source tarball (hashertar).

Note that hasher source tarball (hashertar) is the content of src.rpm packaged 
as tar file suitable for hasher(1).

=head1	OPTIONS

=over

=item	B<-h, --help>

Display this help and exit.

=item	B<-v, --verbose>, B<-q, --quiet>

Verbosity level. Multiple -v increase the verbosity level, -q sets it to 0.
Default is 1.

=item	B<-o, --outdir> I<dirname>

Output directory.

=item	B<-bs, -b, -s> 

Try to write src.rpm first, then fallback to hashertar.

=item	B<--nodeps> 

Ignored for compatibility.

=back

=head1	AUTHOR

Written by Igor Vlasenko <viy@altlinux.org>.

=head1	COPYING

Copyright (c) 2008 Igor Vlasenko, ALT Linux Team.

This 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 2 of the License, or (at your option) any later version.

=cut
