#!/usr/local/bin/perl

use Config;
use File::Basename qw(&basename &dirname);

# List explicitly here the variables you want Configure to
# generate.  Metaconfig only looks for shell variables, so you
# have to mention them as if they were shell variables, not
# %Config entries.  Thus you write
#  $startperl
# to ensure Configure will look for $Config{startperl}.

# This forces PL files to create target in same directory as PL file.
# This is so that make depend always knows where to find PL derivatives.
chdir(dirname($0));
($file = basename($0)) =~ s/\.PL$//;
$file =~ s/\.pl$//
	if ($^O eq 'VMS' or $^O eq 'os2');  # "case-forgiving"

open OUT,">$file" or die "Can't create $file: $!";

print "Extracting $file (with variable substitutions)\n";

# In this section, perl variables will be expanded during extraction.
# You can use $Config{...} to use Configure variables.

print OUT <<"!GROK!THIS!";
$Config{'startperl'}
    eval 'exec perl -S \$0 "\$@"'
	if 0;
!GROK!THIS!

# In the following, perl variables are not expanded during extraction.

print OUT <<'!NO!SUBS!';

=head1 NAME

h2xs - convert .h C header files to Perl extensions

=head1 SYNOPSIS

B<h2xs> [B<-AOPXcdf>] [B<-v> version] [B<-n> module_name] [B<-p> prefix] [B<-s> sub] [headerfile [extra_libraries]]

B<h2xs> B<-h>

=head1 DESCRIPTION

I<h2xs> builds a Perl extension from any C header file.  The extension will
include functions which can be used to retrieve the value of any #define
statement which was in the C header.

The I<module_name> will be used for the name of the extension.  If
module_name is not supplied then the name of the header file will be used,
with the first character capitalized.

If the extension might need extra libraries, they should be included
here.  The extension Makefile.PL will take care of checking whether
the libraries actually exist and how they should be loaded.
The extra libraries should be specified in the form -lm -lposix, etc,
just as on the cc command line.  By default, the Makefile.PL will
search through the library path determined by Configure.  That path
can be augmented by including arguments of the form B<-L/another/library/path>
in the extra-libraries argument.

=head1 OPTIONS

=over 5

=item B<-A>

Omit all autoload facilities.  This is the same as B<-c> but also removes the
S<C<require AutoLoader>> statement from the .pm file.

=item B<-F>

Additional flags to specify to C preprocessor when scanning header for
function declarations. Should not be used without B<-x>.

=item B<-O>

Allows a pre-existing extension directory to be overwritten.

=item B<-P>

Omit the autogenerated stub POD section. 

=item B<-X>

Omit the XS portion.  Used to generate templates for a module which is not
XS-based.

=item B<-c>

Omit C<constant()> from the .xs file and corresponding specialised
C<AUTOLOAD> from the .pm file.

=item B<-d>

Turn on debugging messages.

=item B<-f>

Allows an extension to be created for a header even if that header is
not found in /usr/include.

=item B<-h>

Print the usage, help and version for this h2xs and exit.

=item B<-n> I<module_name>

Specifies a name to be used for the extension, e.g., S<-n RPC::DCE>

=item B<-p> I<prefix>

Specify a prefix which should be removed from the Perl function names, e.g., S<-p sec_rgy_> 
This sets up the XS B<PREFIX> keyword and removes the prefix from functions that are
autoloaded via the C<constant()> mechansim.

=item B<-s> I<sub1,sub2>

Create a perl subroutine for the specified macros rather than autoload with the constant() subroutine.
These macros are assumed to have a return type of B<char *>, e.g., S<-s sec_rgy_wildcard_name,sec_rgy_wildcard_sid>.

=item B<-v> I<version>

Specify a version number for this extension.  This version number is added
to the templates.  The default is 0.01.

=item B<-x>

Automatically generate XSUBs basing on function declarations in the
header file.  The package C<C::Scan> should be installed. If this
option is specified, the name of the header file may look like
C<NAME1,NAME2>. In this case NAME1 is used instead of the specified string,
but XSUBs are emitted only for the declarations included from file NAME2.

Note that some types of arguments/return-values for functions may
result in XSUB-declarations/typemap-entries which need
hand-editing. Such may be objects which cannot be converted from/to a
pointer (like C<long long>), pointers to functions, or arrays.

=back

=head1 EXAMPLES


	# Default behavior, extension is Rusers
	h2xs rpcsvc/rusers

	# Same, but extension is RUSERS
	h2xs -n RUSERS rpcsvc/rusers

	# Extension is rpcsvc::rusers. Still finds <rpcsvc/rusers.h>
	h2xs rpcsvc::rusers

	# Extension is ONC::RPC.  Still finds <rpcsvc/rusers.h>
	h2xs -n ONC::RPC rpcsvc/rusers

	# Without constant() or AUTOLOAD
	h2xs -c rpcsvc/rusers

	# Creates templates for an extension named RPC
	h2xs -cfn RPC

	# Extension is ONC::RPC.
	h2xs -cfn ONC::RPC

	# Makefile.PL will look for library -lrpc in 
	# additional directory /opt/net/lib
	h2xs rpcsvc/rusers -L/opt/net/lib -lrpc

        # Extension is DCE::rgynbase
        # prefix "sec_rgy_" is dropped from perl function names
        h2xs -n DCE::rgynbase -p sec_rgy_ dce/rgynbase

        # Extension is DCE::rgynbase
        # prefix "sec_rgy_" is dropped from perl function names
        # subroutines are created for sec_rgy_wildcard_name and sec_rgy_wildcard_sid
        h2xs -n DCE::rgynbase -p sec_rgy_ \
        -s sec_rgy_wildcard_name,sec_rgy_wildcard_sid dce/rgynbase

	# Make XS without defines in perl.h, but with function declarations
	# visible from perl.h. Name of the extension is perl1.
	# When scanning perl.h, define -DEXT=extern -DdEXT= -DINIT(x)=
	# Extra backslashes below because the string is passed to shell.
	# Note that a directory with perl header files would 
	#  be added automatically to include path.
	h2xs -xAn perl1 -F "-DEXT=extern -DdEXT= -DINIT\(x\)=" perl.h

	# Same with function declaration in proto.h as visible from perl.h.
	h2xs -xAn perl2 perl.h,proto.h

=head1 ENVIRONMENT

No environment variables are used.

=head1 AUTHOR

Larry Wall and others

=head1 SEE ALSO

L<perl>, L<perlxstut>, L<ExtUtils::MakeMaker>, and L<AutoLoader>.

=head1 DIAGNOSTICS

The usual warnings if it cannot read or write the files involved.

=cut

my( $H2XS_VERSION ) = ' $Revision: 1.1 $ ' =~ /\$Revision:\s+([^\s]+)/;


use Getopt::Std;
use ExtUtils::DynaGlue ();

sub usage{
	warn "@_\n" if @_;
    die "h2xs [-AOPXcdfh] [-v version] [-n module_name] [-p prefix] [-s subs] [headerfile [extra_libraries]]
version: $H2XS_VERSION
    -A   Omit all autoloading facilities (implies -c).
    -F   Additional flags for C preprocessor (used with -x).
    -O   Allow overwriting of a pre-existing extension directory.
    -P   Omit the stub POD section.
    -X   Omit the XS portion.
    -c   Omit the constant() function and specialised AUTOLOAD from the XS file.
    -d   Turn on debugging messages.
    -f   Force creation of the extension even if the C header does not exist.
    -h   Display this help message
    -n   Specify a name to use for the extension (recommended).
    -p   Specify a prefix which should be removed from the Perl function names.
    -s   Create subroutines for specified macros.
    -v   Specify a version number for this extension.
    -x   Autogenerate XSUBs using C::Scan.
extra_libraries
         are any libraries that might be needed for loading the
         extension, e.g. -lm would try to link in the math library.
";
}

getopts("AF:OPXcdfhn:p:s:v:x") || usage;

usage if $opt_h;

$opt_c = 1 if $opt_A;
$path_h = shift;

my $glue = new ExtUtils::DynaGlue
    NO_XS       => $opt_X,
    NO_CONST    => $opt_c,
    NO_AUTO     => $opt_A,
    NO_POD      => $opt_P,
    NAME        => $opt_n,
    PREFIX      => $opt_p,
    CONST_XSUBS => $opt_s,
    PATH_H      => $path_h,
    DO_SCAN     => $opt_x,
    FLAGS       => $opt_F,
    EXTRALIBS   => "@ARGV",
    TEMPLATE_VERSION => $opt_v,
    VERBOSE => 1,
    ;

usage "Must supply header file or module name\n"
	unless ($path_h or $opt_n);

if( $path_h ){
    $name = $path_h;
    if( $path_h =~ s#::#/#g && $opt_n ){
	warn "Nesting of headerfile ignored with -n\n";
    }
    $path_h = $glue->path_h; 
    if (!$opt_c) {
      die "Can't find $path_h\n" if ( ! $opt_f && ! -f $path_h );
    }
}

chdir $ext if($ext = $glue->ext);

($modfname, $modpname, $modparts) = $glue->modparts;

if ($opt_O) {
	warn "Overwriting existing $ext$modpname!!!\n" if -e $modpname;
} else {
	die "Won't overwrite existing $ext$modpname\n" if -e $modpname;
}

$glue->mkdirs($modpname, $modparts);

chdir($modpname) || die "Can't chdir $ext$modpname: $!\n";

#write_* methods can also take a filename as the first argument,
#otherwise default to the standard names in the current directory

for (qw(xs pm typemap makefilepl test changes manifest)) {
    $method = "write_$_";
    $glue->$method();
}

!NO!SUBS!

close OUT or die "Can't close $file: $!";
chmod 0755, $file or die "Can't reset permissions for $file: $!\n";
exec("$Config{'eunicefix'} $file") if $Config{'eunicefix'} ne ':';
