#!/usr/bin/env perl
##----------------------------------------------------------------------------
## Person Name Format - scripts/generate_script_names.pl
##
## Generates lib/PersonName/Format/ScriptNames.pl from the Unicode character
## database bundled with the running Perl installation.
##
## Usage:
##   perl scripts/generate_script_names.pl > lib/PersonName/Format/ScriptNames.pl
##
## This script should be re-run whenever the minimum supported Perl version
## changes, or when adding support for a new Perl version that ships a newer
## Unicode standard with additional scripts.
##
## The output file maps Unicode script long names (as returned by
## Unicode::UCD::charscript()) to ISO 15924 four-letter codes. It is used by
## PersonName::Format::PP::_script_code_for_uv() on Perl versions older than
## v5.16.0, where Unicode::UCD::prop_value_aliases() is not available.
##----------------------------------------------------------------------------
use strict;
use warnings;
use Unicode::UCD qw( charscripts );

my $scripts = charscripts();

# NOTE: 'Unknown' is returned by charscript() for private-use and unassigned codepoints,
# but is not a key in charscripts().  Add it explicitly.
my %all = ( %$scripts, Unknown => [] );

printf( "# !!!!!!!   DO NOT EDIT THIS FILE   !!!!!!!\n" );
printf( "# This file is auto-generated by scripts/generate_script_names.pl\n" );
printf( "# from the Unicode character database bundled with the running Perl.\n" );
printf( "# It maps Unicode script long names (as returned by\n" );
printf( "# Unicode::UCD::charscript()) to ISO 15924 four-letter codes.\n" );
printf( "#\n" );
printf( "# Regenerate with:\n" );
printf( "#   perl scripts/generate_script_names.pl > lib/PersonName/Format/ScriptNames.pl\n" );
printf( "#\n" );
printf( "# Generated by Perl %s (Unicode %s) on %s\n",
    $],
    Unicode::UCD::UnicodeVersion(),
    do{ my @t = localtime; sprintf( '%04d-%02d-%02d', $t[5]+1900, $t[4]+1, $t[3] ) }
);
printf( "\n" );
printf( "%%PersonName::Format::PP::SCRIPT_NAME_TO_CODE = (\n" );

foreach my $name ( sort( keys( %all ) ) )
{
    # NOTE: prop_value_aliases() returns the ISO 15924 code as its first element.
    # It is available on Perl 5.16 and later, which is the same condition under which
    # this file would not be needed.  On older Perls we use charscripts() keys directly
    # and rely on prop_value_aliases() being present to generate this file from a newer Perl.
    my @aliases = Unicode::UCD::prop_value_aliases( 'sc', $name );
    my $code    = $aliases[0] // 'Zzzz';
    printf( "    %-35s => '%s',\n", "'$name'", $code );
}

printf( ");\n\n" );
printf( "1;\n\n" );
print( "__END__\n" );

__END__
