1#!/usr/bin/perl
2# This script isn't supposed to be run by hand, it's used by `make` as a pre-
3# processor. It currently accepts two kinds of options on the command line:
4#   -M<module>            Enables <module>
5#   -D<variable>=<value>  Defines the <variable> to be <value>
6#
7# Those modules are currently implemented:
8#   conditional          Comments out every line containing the string
9#                        REMOVEFORINST
10#   vars                 Replaces variables. Are upper case strings surrounded
11#                        by double at-signs, eg. @@VERSION@@. The values are
12#                        taken from the environment and can be overwritten with
13#                        the -D switch. Empty/undefined variables are removed.
14#   sharpbang            Does some sharpbang (#!) replacement. See code below.
15#
16
17use Config;
18
19my %modules = ();
20my %defines = ();
21
22foreach (keys %ENV) {
23    $defines{$_} = $ENV{$_};
24}
25
26foreach (@ARGV) {
27    if    (/^-M([a-z]+)$/)       { $modules{$1} = 1; }
28    elsif (/^-D([A-Z_]+)=(.*)$/) { $defines{$1} = $2; }
29}
30
31my $l = 1;
32foreach (<STDIN>) {
33
34    # Conditional compiling
35    if ($modules{'conditional'}) {
36
37        # Comment out lines carrying the REMOVEFORINST tag
38        if (/\bREMOVEFORINST\b/) {
39            s/^(\s*)/$1#/;
40            s/REMOVEFORINST/REMOVEDBYINST/;
41        }
42    }
43
44    # Variable replacement
45    if ($modules{'vars'}) {
46
47        # Replace all @@VARS@@
48        s/\@\@([A-Z][A-Z0-9_]*)\@\@/$defines{$1}/g;
49    }
50
51    # Sharpbang (#!) replacement (see also ExtUtils::MY->fixin)
52    if ($modules{'sharpbang'} && ($l == 1)) {
53
54        # The perlpath can be overwritten via -DPERL_BIN=<perlpath>
55        my $perl = $defines{'PERL_BIN'} || $Config{'perlpath'};
56
57        # If we're using a CVS build, add the -w switch to turn on warnings
58        my $minusw = -f 'CVS/Repository' ? ' -w' : '';
59
60        # The warnings can be overwritten via -DPERL_WARN=<1|0>
61        if (defined $defines{'PERL_WARN'}) {
62            $minusw = $defines{'PERL_WARN'} ? ' -w' : '';
63        }
64        s/^#!.*perl.*$/#!${perl}${minusw}/;
65    }
66
67    print;
68    $l++;
69}
70