a008c1
#! /usr/bin/perl -w
a008c1
a008c1
# This program is free software; you can redistribute it and/or
a008c1
# modify it under the terms of the GNU General Public License
a008c1
# as published by the Free Software Foundation; either version 2
a008c1
# of the License, or (at your option) any later version.
a008c1
#
a008c1
# This program is distributed in the hope that it will be useful,
a008c1
# but WITHOUT ANY WARRANTY; without even the implied warranty of
a008c1
# MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
a008c1
# GNU General Public License for more details.
a008c1
#
a008c1
# You should have received a copy of the GNU General Public License
a008c1
# along with this program; if not, write to the Free Software
a008c1
# Foundation, Inc., 59 Temple Place - Suite 330, Boston, MA  02111-1307,
a008c1
# USA.
a008c1
a008c1
use Getopt::Long qw(:config gnu_getopt);
a008c1
a008c1
sub rpm_cmp_versions {
a008c1
    my ($evr1, $evr2) = @_;
a008c1
a008c1
    sub _rpm_cmp {
a008c1
	my ($s1, $s2) = @_;
a008c1
a008c1
	return defined $s1 <=> defined $s2
a008c1
	    unless defined $s1 && defined $s2;
a008c1
a008c1
	my ($r, $x1, $x2);
a008c1
	do {
a008c1
	    $s1 =~ s/^[^a-zA-Z0-9]+//;
a008c1
	    $s2 =~ s/^[^a-zA-Z0-9]+//;
a008c1
	    if ($s1 =~ /^\d/ || $s2 =~ /^\d/) {
a008c1
		$s1 =~ s/^0*(\d*)//;  $x1 = $1;
a008c1
		$s2 =~ s/^0*(\d*)//;  $x2 = $1;
a008c1
		$r = length $x1 <=> length $x2 || $x1 cmp $x2;
a008c1
	    } else {
a008c1
		$s1 =~ s/^([a-zA-Z]*)//;  $x1 = $1;
a008c1
		$s2 =~ s/^([a-zA-Z]*)//;  $x2 = $1;
a008c1
		return 0
a008c1
		    if $x1 eq '' && $x2 eq '';
a008c1
		$r = $x1 cmp $x2;
a008c1
	    }
a008c1
	} until $r;
a008c1
	return $r;
a008c1
    }
a008c1
a008c1
    my ($e1, $v1, $r1) = $evr1 =~ /^(?:(\d*):)?(.*?)(?:-([^-]*))?$/;
a008c1
    my ($e2, $v2, $r2) = $evr2 =~ /^(?:(\d*):)?(.*?)(?:-([^-]*))?$/;
a008c1
    my $r = _rpm_cmp($e1 || 0, $e2 || 0);
a008c1
    $r = _rpm_cmp($v1, $v2)
a008c1
	unless $r;
a008c1
    $r = _rpm_cmp($r1, $r2)
a008c1
	unless $r;
a008c1
    return $r;
a008c1
}
a008c1
a008c1
my $reorder = sub { return @_ };
a008c1
my $key = 0;
a008c1
a008c1
GetOptions ("r|reverse"	    => sub { $reorder = sub { return reverse @_ } },
a008c1
	    "k|key=i"	    => \$key)
a008c1
or do {
a008c1
    print STDERR "Usage\n";
a008c1
    exit 1;
a008c1
};
a008c1
a008c1
if ($key == 0) {
a008c1
    # Sort by entire lines
a008c1
    map { print } &$reorder(sort { rpm_cmp_versions($a, $b) } <>);
a008c1
} else {
a008c1
    # Sort by field $key
a008c1
    my @data = map { [(split)[$key-1], $_] } <>;
a008c1
    map { print } &$reorder(map { $_->[1] }
a008c1
        sort { rpm_cmp_versions($a->[0], $b->[0]) } @data);
a008c1
}