#!/usr/bin/perl -w
################################################################################
#
#  scanprov -- scan Perl headers for provided macros
#
################################################################################
#
#  $Revision: 5 $
#  $Author: mhx $
#  $Date: 2005/01/31 08:10:50 +0100 $
#
################################################################################
#
#  Version 3.x, Copyright (C) 2004-2005, Marcus Holland-Moritz.
#  Version 2.x, Copyright (C) 2001, Paul Marquess.
#  Version 1.x, Copyright (C) 1999, Kenneth Albanowski.
#
#  This program is free software; you can redistribute it and/or
#  modify it under the same terms as Perl itself.
#
################################################################################

use strict;
require 'parts/ppptools.pl';

die "Usage: $0 [check|write]\n" unless @ARGV && $ARGV[0] =~ /^(check|write)$/;
my $mode = $1;

my %embed = map { ( $_->{name} => 1 ) }
            parse_embed(qw(parts/embed.fnc parts/apidoc.fnc));

my @provided = grep { !exists $embed{$_} }
               map { /^(\w+)/ ? $1 : () }
               `$^X ppport.h --list-provided`;

my $install = '/tmp/perl/install/default';

my @perls = sort { $b->{version} <=> $a->{version} }
            map { { version => `$_ -e 'printf "%.6f", \$]'`, path => $_ } }
            ('bleadperl', glob "$install/*/bin/perl5.*");

for (1 .. $#perls) {
  $perls[$_]{todo} = $perls[$_-1]{version};
}

shift @perls;

my %v;

for my $p (@perls) {
  print "checking perl $p->{version}...\n";
  my $archlib = `$p->{path} -MConfig -l -e 'print \$Config{archlib}'`;
  chomp $archlib;
  local @ARGV = glob "$archlib/CORE/*.h";
  my %sym;
  while (<>) { $sym{$_}++ for /(\w+)/g; }
  @provided = map { $sym{$_} or $v{$p->{todo}}{$_}++; $sym{$_} ? $_ : () } @provided;
}

my $out = 'parts/base';
my $todo = parse_todo($out);

for my $v (keys %v) {
  my @new = sort grep { !exists $todo->{$_} } keys %{$v{$v}};
  @new or next;
  my $file = $v;
  $file =~ s/\.//g;
  $file = "$out/$file";
  -e $file or die "non-existent: $file\n";
  print "-- $file --\n";
  $mode eq 'write' and (open F, ">>$file" or die "$file: $!\n");
  for (@new) {
    print "adding $_\n";
    $mode eq 'write' and printf F "%-30s # added by $0\n", $_;
  }
  $mode eq 'write' and close F;
}
