#!/usr/local/bin/perl
#
# preambulate -- wrap a perl program with a system-independent preamble.  
#
# Tom Christiansen tchrist@convex.com

$mypath = '/usr/local/bin/perl';
($myversion, $mypatchlevel) = $] =~ /(\d+\.\d+).*\nPatch level: (\d+)/;


unless (@ARGV) {
    unshift(@ARGV, '-');
    $was_stdin++;
}

while ($file = shift) {
    open file || die "can't open $file: $!";
    $mode = (stat(file))[2] & 0777;
    if ($file ne '-') {
	$TMP = "$file.tmp";
	open (TMP, ">$TMP") || die "can't create $TMP: $!"; 
     } else {
	open (TMP, ">&STDOUT");
     } 
     print TMP <<'EOF';
#!/bin/sh -- need to mention perl here to avoid recursion

'true' || eval 'exec perl -S $0 $argv:q';
eval '(exit $?0)' && eval 'exec perl -S $0 ${1+"$@"}'
& eval 'exec perl -S $0 $argv:q'
        if 0;

VERSION_SANITY: {
    package VERSION_SANITY;
    local($_);
EOF
    print TMP <<"EOF";
    \$PERL_PATH = '$mypath';
    local(\$version, \$patchlevel) = ($myversion, $mypatchlevel);
EOF

    print TMP <<'EOF';

    local($want_vp) = sprintf("%d.%03d", $version, $patchlevel);
    local($need_perl) = $PERL_PATH . $want_vp;

    die "can't get version" 
	unless $] =~ /(\d+\.\d+).*\nPatch level: (\d+)/;

    sub try_version {
        warn "current perl version ($got_vp) too low, execing $need_perl\n";
        exec $need_perl, $0, @ARGV;
        warn "exec of $need_perl failed: $!";
    }

    if ($1 < $version || $2 < $patchlevel) { 
	local($got_vp) =  sprintf("%d.%03d", $1, $2);
        &try_version if -x $need_perl;
        for $need_perl (reverse sort </usr/local/bin/perl* /usr/bin/perl*>) {
            next unless $need_perl =~ /perl(\d+)\.(\d+)$/;
            &try_version if $1 >= $version && $2 >= $patchlevel;
        }
        warn "WARNING: perl version too low: $got_vp < $want_vp; good luck...\n";
    } 
} 

eval <<'___VERSION_SANITY___';

# BEGIN REAL PROGRAM

EOF

    while (<file>) {
	print TMP;
    } 

    print TMP <<'EOF';


# END REAL PROGRAM

___VERSION_SANITY___

die "$0: OOPS, YOU LOSE: $@" if $@;

exit 0;

EOF

    unless ($file eq '-') {
	close TMP;
	chmod $mode, $TMP;
	rename ($file, "$file.bak") || die "can't rename $file to $file.bak: $!";
	rename ($TMP, $file) || die "can't rename $TMP to $file: $!";
    }
}
