#!/usr/bin/env perl

=head1 NAME

ver_cpan2pacman

=head1 USAGE

  ver_cpan2pacman [CPAN versions]

=head1 DESCRIPTION

Convert CPAN versions to canonicalized Pacman package version that enable pacman
to correctly compare CPAN packakges.

This uses the "version" module, which is authoritative according to the CPAN
Meta Spec:

http://search.cpan.org/~dagolden/CPAN-Meta-2.110440/lib/CPAN/Meta/Spec.pm#Version_Formats
http://search.cpan.org/search?query=version&mode=dist
http://search.cpan.org/~jpeacock/version-0.88/lib/version/Internals.pod

=head1 AUTHOR

Xyne <ac xunilhcra enyx, backwards>

=head1 COPYRIGHT AND LICENSE

Copyright (C) 2011  Xyne

This program is free software; you can redistribute it and/or
modify it under the terms of the GNU General Public License
(version 2) as published by the Free Software Foundation.

This program is distributed in the hope that it will be useful,
but WITHOUT ANY WARRANTY; without even the implied warranty of
MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
GNU General Public License for more details.

You should have received a copy of the GNU General Public License
along with this program; if not, write to the Free Software
Foundation, Inc., 51 Franklin Street, Fifth Floor, Boston, MA  02110-1301, USA.

=cut


use strict;
use warnings;

use version;

sub cpan_to_pacman
{
  my $ver = shift;
  return 'undef' if not defined($ver);

  # Check if the version is parsable via the "version" module. If not, return
  # "undef".
  if ($ver !~ m/^$version::STRICT$/ and $ver !~ m/^$version::LAX$/)
  {
    print STDERR "Invalid version string: $ver\n";
    return 'undef';
  }
  $ver = version->parse($ver)->numify;

  # Underscores are considered "alpha" versions. Replace them with "a" so that
  # Pacman treats them as alpha versions too.
  $ver =~ s/_/a\./;

  # Versions that expand to 6 decimal places should be broken up into 2 groups
  # of 3 digits. See the "Decimal Versions" section of the "version::Internals"
  # POD.
  $ver =~ s/(?<=\.)(\d{3})(\d{3})$/${1}.${2}/;

  return $ver;
}

foreach my $ver (@ARGV)
{
  my $pkgver = &cpan_to_pacman($ver);
  print "$ver -> $pkgver\n";
}
