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

usage() if $opt_h;

my $lang = shift;

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

eval 'use Math::Currency 0.40';
if ( $@ ) { # not already installed
    die "Math::Currency 0.40 required to create new currencies\n" .
    "Please install a current Math::Currency before proceeding\n";
}

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 \$LANG);

\$VERSION = $Math::Currency::VERSION;
\$LANG  = '$lang';
\@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 not $opt_f and -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:

    perl scripts/new_currency -f [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 unless you also include the '-f' option.

    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);
}
