#!/usr/bin/env perl
#
# produce the table which knows which constant/function is provided
# by which module.  This produces a new POSIX/1003/Symbols.pm

use blib;

use POSIX::1003   qw(posix_1003_modules posix_1003_names);
use POSIX::1003::Symbols;

my $symbols = $INC{'POSIX/1003/Symbols.pm'}
    or die "cannot find filename for POSIX::1003::Symbols";
#warn "writing $symbols";

-w $symbols || chmod 0644, $symbols
    or die "cannot make $symbols writable: $!";

open SYMBOLS, '>', $symbols
    or die "cannot write to $symbols: $!";

my $now = localtime;

print SYMBOLS <<_HEAD;
# Warning: generated during module installation
#  by $0
#  at $now
# do not edit this file by hand!

package POSIX::1003;

our %EXPORT_TAGS = (
_HEAD

my %subsets;
foreach my $mod (posix_1003_modules)
{   my $tag   = POSIX::1003::_mod2tag($mod);
    my $names = posix_1003_names ":$tag";

    my $et = \%{$mod.'::EXPORT_TAGS'};
    push @{$subsets{$tag}}, keys %$et;

    my @names = sort {lc $a cmp lc $b} keys %$names;
    local $"  = "\n  ";
    print SYMBOLS "$tag => [ qw(\n  @names\n  ) ],\n"
}
print SYMBOLS ");\n\n# shorter aliases:\n";

my @all_tags = POSIX::1003::_tags();
foreach my $tag (sort @all_tags)
{   my ($mod) = POSIX::1003::_tag2mods($tag);
    my $long  = POSIX::1003::_mod2tag($mod);
    printf SYMBOLS "\$EXPORT_TAGS%-10s = \$EXPORT_TAGS{$long};\n", "{$tag}"
        if $long ne $tag;
}
print SYMBOLS "\n\n# sub-set exports:\n";

my %generic_export = map +($_ => 1), qw/functions tables constants actions/;

foreach my $tag (sort keys %subsets)
{   printf SYMBOLS "\$SUBSET%-10s = '$tag';\n", "{$_}"
        for grep !$generic_export{$_}, @{$subsets{$tag}};
}

print SYMBOLS <<_TAIL;

1;
_TAIL

close SYMBOLS
    or die "write errors to $symbols: $!";
