# Write out the perl5i wrapper C program making sure it uses
# the Perl its built with.

my $file = shift;

# Its going inside double quotes.
my $perl_path = $^X;
$perl_path =~ s{ ([\\"]) }{\\$1}gx;

open my $fh, ">", $file or die $!;
printf $fh <<'END', $0, $perl_path;
/* THIS FILE IS GENERATED BY %s
 * Any changes here will be wiped out.  Edit it there instead.
 */

#include <unistd.h>
#include <stdlib.h>
#include <stdio.h>
#include <string.h>

/*
 * Meant to mimic the shell command
 *     exec perl -Mperl5i::latest "$@"
 *
 * This is a C program so it works in a #! line.
 */

int main (int argc, char* argv[]) {
    int i;
    const char* perl_cmd = "%s";
    char* perl_args[argc+1];
    char* dash_m = (char *)malloc(sizeof(char) * (strlen(argv[0]) + 20));

    strcat(dash_m, "-Mperl5i::cmd=");
    strcat(dash_m, argv[0]);

    perl_args[0] = (char *)perl_cmd;
    perl_args[1] = dash_m;

    for( i = 1;  i < argc;  i++ ) {
        #if defined(WIN32)
            /* Windows arguments aren't really a list but a single string,
             * execv() fakes it, so we need to put the quotes back.
             */
            char* wrapped_arg = (char *)malloc( strlen(argv[i]) + 3 );
            sprintf(wrapped_arg, "\"%%s\"", argv[i]);
            perl_args[i+1] = wrapped_arg;
        #else
            perl_args[i+1] = argv[i];
        #endif
    }

    /* Argument array must be terminated by a null */
    perl_args[argc+1] = (char *)NULL;

    return execv( perl_cmd, perl_args );
}
END
