#!/usr/bin/perl
#
# Convert bank account numbers into IBAN/SEPA numbers.
# Based on Business::IBAN from package perl-Business-IBAN.
#
use strict;
use Business::IBAN;
use Locale::Country;
use POSIX;
use warnings;

sub usage {
    my $ret = shift;
    print STDERR "$0: Usage:\n";
    print STDERR "    $0 [2_Letter_Country_Code] BLZ AC\n";
    print STDERR "    $0 [2_Letter_Country_Code] BBAN\n";
    exit $ret;
}

package main;
setlocale(LC_MONETARY,"");

my $locale;
my $hascc = 0;
if ($#ARGV < 0 || $#ARGV > 2) {
    usage(2);
}
if ($ARGV[0] =~ /^[A-Z][A-Z]$/) {
    $locale = $ARGV[0];
    $hascc = 1;
} else {
    $locale = setlocale(LC_MONETARY);
    $locale =~ s/[a-z][a-z]_([A-Z][A-Z])(\..*)?/$1/;
}
if ($locale eq "C" || $locale eq "POSIX") {
    usage(1);
    exit(1);
}
my $lang = code2country($locale);
if (! $lang) {
    print STDERR "$0: Broken 2 Letter Country Code \`$locale'\n";
    usage(3);
}
my $iso  = country2code($lang, LOCALE_CODE_DOM);
my $iban = Business::IBAN->new();
my @array;

if ($#ARGV == 0) {
    @array = {	ISO => $iso,
		BBAN => $ARGV[0]
	     };
} elsif ($#ARGV == 1) {
    if ($hascc > 0) {
	@array = {  ISO => $iso,
		    BBAN => $ARGV[1]
		 };
    } else {
	@array = {  ISO => $iso,
		    BIC => $ARGV[0],
		    AC => $ARGV[1]
		 };
    }
} else {
    @array = {	ISO => $iso,
		BIC => $ARGV[1],
		AC => $ARGV[2]
	     };
}
if (my $num = $iban->getIBAN(@array)) {
    print $num . "\n";
} else {
    $iban->printError();
}

__END__

=head1 NAME

iban - convert AC and BIC of the bank into an IBAN 

=head1 SYNOPSIS

B<iban> [B<CC>] B<BIC> B<AC>

B<iban> [B<CC>] B<BBAN>

=head1 DESCRIPTION

The script B<iban> converts  Account Code (AC) and the Bank Identifier Code (BIC) into the International Bank Account Number (IBAN). Instead of the AC and BIC  B<iban> also accepts the a Basic Bank Account Number (BBAN).  It also tries to use to determine from the current B<locale>(7) the Country Code (CC) as defined in ISO 3166. If the current B<locale>(7) does not provides a valid CC, like for I<POSIX> or I<C> B<locale>(7), the two letter Country Code has to be the first argument.

=head1 SEE ALSO

Business::IBAN
