#!/usr/bin/perl

use strict;

my($usage) = "Usage: rpmcmp <epoch1> <version1> <release1> <epoch2> <version2> <release2>";

sub chop_head (\$) {
    my ($ref) = @_;
    $$ref =~ /^[^\da-zA-Z]*((\d+)|([a-zA-Z]+))(.*)$/;
    $$ref = $4;
    $1;
}

sub rpm_ver_cmp ($$) {
    my ($a, $b) = @_;
    while(1) {
        my $aa = chop_head $a;
        my $bb = chop_head $b;
 
        return defined($aa) - defined($bb) unless defined($aa) && defined($bb);
 
        my $c = "$aa$bb" =~ /\D/ ? $aa cmp $bb : $aa <=> $bb;
        return $c if $c;
    }
}

sub arch_evr_compare ($$$$$$) {
    my ($aa, $bb) = @_;
    my ($a_ep, $a_ver, $a_rel, $b_ep, $b_ver, $b_rel) = @_;
 
    return $a_ep <=> $b_ep if $a_ep <=> $b_ep;
    my $c_ver = rpm_ver_cmp($a_ver, $b_ver);
    return $c_ver if $c_ver;
    return rpm_ver_cmp($a_rel, $b_rel);
}

my $epoch1 = shift || die $usage;
my $version1 = shift || die $usage;
my $release1 = shift || die $usage;
my $epoch2 = shift || die $usage;
my $version2 = shift || die $usage;
my $release2 = shift || die $usage;

if($epoch1 == "(none)") {
    $epoch1 = 0;
}

if($epoch2 == "(none)") {
    $epoch2 = 0;
}

my $result = arch_evr_compare($epoch1, $version1, $release1, $epoch2, $version2, $release2);
if ($result == 0) {
    exit 0;
} elsif ($result == 1) {
    exit 1;
} elsif ($result == -1) {
    exit 2;
}

