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