#!/usr/bin/perl -w
use Getopt::Std;
use vars qw( $opt_h );
getopts('h');

usage() if $opt_h;

my $locale = shift;

if ($locale) {
    eval '
	use POSIX qw( locale_h );
	my $locale = setlocale( LC_ALL, "$locale" );
    ';
    die "Cannot use this locale: $@" if $@;
}

eval 'use Math::Currency 0.40';
if ( $@ and -d "./lib") { # not already installed
    push @INC, "./lib";   # and in the top level build directory
    eval 'use Math::Currency 0.40';
    die "Cannot load Math::Currency: $@" if $@;
}

my $format = {};
die "Cannot determine your locale currency format"
    unless Math::Currency->localize( \$format );

my $localename = $format->{INT_CURR_SYMBOL};
$localename =~ s/([A-Z]{3})./$1/;
my $localesub = <<EOL;
#!/usr/bin/perl -w
package Math::Currency::$localename;

use Exporter;
use Math::Currency qw(\$LC_MONETARY \$FORMAT);
use vars qw(\$VERSION \@ISA);

\$VERSION = 0.01;
\@ISA     = qw(Exporter Math::Currency);

\$LC_MONETARY->{$localename} = {
EOL

foreach my $param qw(
  INT_CURR_SYMBOL CURRENCY_SYMBOL MON_DECIMAL_POINT
  MON_THOUSANDS_SEP MON_GROUPING POSITIVE_SIGN
  NEGATIVE_SIGN INT_FRAC_DIGITS FRAC_DIGITS
  P_CS_PRECEDES P_SEP_BY_SPACE N_CS_PRECEDES
  N_SEP_BY_SPACE P_SIGN_POSN N_SIGN_POSN
  )    # hardcoded keys to be sure they are all there
{
    die "Missing $param from locale; cannot proceed"
    	unless defined $format->{$param};

    $localesub .= "\t$param\t=>\t'$format->{$param}',\n";

}
$localesub .= "};\n\n1;\n";

my $filename = "lib/Math/Currency/$localename.pm";

die "The $localename locale has already been generated" if -f $filename;
print STDOUT "Outputting subclass for $localename\n";

open LOCALE, ">", $filename
    or die "Cannot open the module output file: $filename";

print LOCALE $localesub;
close LOCALE;
exit (0);

sub usage {
    print STDOUT <<EOL;
USAGE:

    scripts/new_currency [locale]

    Create a new currency format module.  If the locale is not specified;
    attempt to use the current locale settings.  Otherwise, load the
    specified locale and attempt to use that instead.  Use the standard 
    names for locale's as returned by `locale -a` e.g. en_GB.

    The program will attempt to create a module in the following directory:

    	lib/Math/Currency/

    so the script should be run from the base of the Math::Currency build
    tree.  If the requested locale format file already exists, the
    program will stop with an error.

    Once you have built all of the additional locale subclasses, you can 
    rerun `./Build install` and the additional files will be added to your
    local Perl installation.
EOL
    exit(1);
}
