#!/usr/bin/perl -w

#use strict;
use warnings;
use Carp;
use Getopt::Long;
use RPM::Source::Editor;
use File::Basename;

my ($altsrpm,$altspec,@hooklist,$changelog,@pkglist,$release);
my ($nmumode,$diffmode);
my $verbose=1;
my $outputdir='.';
my $patchdir=dirname($0)."/patches";
$changelog='- NMU (by repocop): the following fixes applied:'."\n" if !$diffmode or $nmumode;

my $result = GetOptions ("pkgname=s" => \@pkglist,
		      "srpm=s"   => \$altsrpm,
		      "spec=s"   => \$altspec,
		      "out=s"   => \$outputdir,
		      "test=s"   => \@hooklist,
		      "changelog=s"   => \$changelog,
		      "release=s"   => \$release,
		      "diff"   => \$diffmode,
		      "nmu"   => \$nmumode,
		      "verbose+"  => \$verbose);
my ($alt);

if ((! $altsrpm || ! $altspec) && ! scalar @pkglist  && ! scalar @hooklist) {
    print "ERROR: one of --srpm | --spec is required!\n";
    print "options:
--alt /path/to/altlinux.src.rpm
--altspec /path/to/altlinux.spec
--test csv list of tests
--out  /path/to/output_dir
--diff write spec diff
--changelog '- message'
--release 'release' - if we need to adjust the package's release

usage examples:
TODO
";
    exit (64);
}

$alt=RPM::Source::Editor->new(
    SOURCERPM => $altsrpm, 
    SPECFILE=> $altspec, 
    OUTPUTDIR=> $outputdir, 
    PATCHDIR=>$patchdir, 
    VERBOSE=> $verbose, 
    CHANGELOG=>$changelog
    );

if ($nmumode) {
    my $altrel = $alt->get_section('package','')->get_tag('Release', RAW=>1);
    my $newrel = $altrel.".qa1";
    if ($altrel=~/\.qa(\d+)$/) {
	$newrel = $altrel.".qa".($1+1);
    }
    $newrel=$release if ($release);
    $alt->get_section('package','')->set_tag('Release',$newrel);
}

# our -- hack ?
our $alttoolsdir=dirname($0);
# for cross-references in hooks
push @INC, $alttoolsdir.'/fixscripts';
push @INC, '/usr/share/repocop/fixscripts';

my @hooks=split(',',join(',',@hooklist));
my @pkg=split(',',join(',',@pkglist));


my %unique_hooks=map {$_=>1} @hooks;
my %hookmap;
our @SPECHOOKS;
foreach my $hook (keys %unique_hooks) {
    eval {
	require $hook.'.pl';
    };
    warn "can't repair $hook\n" if $@;
    $hookmap{$hook}=$SPECHOOKS[0] if @SPECHOOKS;
    $#{SPECHOOKS}=-1;
}
if (@hooks) {
#	$alt->{WARN_NOTAPPLIED}++;
    my $i=0;
    for ($i=0;$i<@hooks;$i++) {
	print STDERR "$hooks[$i] for $pkg[$i]\n" if $verbose and $verbose>1;
	$hookmap{$hooks[$i]}($alt,$pkg[$i]);
	$alt->append_changelog(" * $hooks[$i] for $pkg[$i]\n") if $nmumode;
    }
#	$alt->{WARN_NOTAPPLIED}--;
} else {
    die "script hooks are invalid!\n";
}

if ($changelog) {
    $alt->set_changelog($changelog);
}

print $alt->get_spec() if $altspec or $verbose>1;
$alt->write_rpm() if $altsrpm && !$diffmode;
$alt->write_diff() if $diffmode;
$alt->cleanup();

1;
