/*
 * Copyright (c) 1990 The Ohio State University.
 * All rights reserved.
 *
 * Redistribution and use in source and binary forms are permitted
 * provided that: (1) source distributions retain this entire copyright
 * notice and comment, and (2) distributions including binaries display
 * the following acknowledgement:  ``This product includes software
 * developed by The Ohio State University and its contributors''
 * in the documentation or other materials provided with the distribution
 * and in all advertising materials mentioning features or use of this
 * software. Neither the name of the University nor the names of its
 * contributors may be used to endorse or promote products derived
 * from this software without specific prior written permission.
 * THIS SOFTWARE IS PROVIDED ``AS IS'' AND WITHOUT ANY EXPRESS OR
 * IMPLIED WARRANTIES, INCLUDING, WITHOUT LIMITATION, THE IMPLIED
 * WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE.
 */

/*
 * Compile with -DPERL=path-to-perl -DSCRIPT=script-path 
 *        -DSTRRCHR=(rindex|strrchr) [-DSETSAME]
 */

#include <stdio.h>

extern char **environ;

#ifndef NULL
#define NULL	0
#endif

main(argc, argv)
int argc;
char *argv[];

{
    char **newargv;
    int i, j;
#ifdef SETSAME
    int euid, egid;
#endif
    char *program_name;
    char scriptpath[1024];
    char *lastslash;
    char *STRRCHR();

    program_name = (char *) STRRCHR(*argv, '/');
    if (program_name == NULL)  {
	    program_name = *argv;
    } else {
	    program_name++;
    }

    strcpy(scriptpath, SCRIPT);
    strcat(scriptpath, "/");
    strcat(scriptpath, program_name);
    strcat(scriptpath, ".perl");
      
    argc--; argv++;

    newargv = (char **) malloc(argc + 3);
    if (newargv == NULL) {
	fprintf(stderr, "%s wrapper: cannot malloc enough space for argv!\n", 
		SCRIPT);
	exit(1);
    }

    j = 0;
    if ((lastslash = STRRCHR(PERL, '/')) == NULL) {
	newargv[j++] = PERL;
    } else {
        newargv[j++] = lastslash+1;
    }
    newargv[j++] = "-I";
    newargv[j++] = SCRIPT;
    newargv[j++] = scriptpath;

    for (i = 0; i < argc; i++) {
	newargv[j++] = argv[i];
    }
    newargv[j] = NULL;

#ifdef SETSAME
    euid = geteuid();
    egid = getegid();

#ifdef SETUID
    if (setuid(euid) != 0) {
	perror("can't do setuid");
    }

    if (setgid(egid) != 0) {
	perror("can't do setgid");
    }
#else
#ifndef SETRESUID
    if (setreuid(euid, euid) != 0) {
	perror("can't do setreuid");
    }

    if (setregid(egid, egid) != 0) {
	perror("can't do setregid");
    }
#else
    if (setresuid(euid, euid, -1) != 0) {
	perror("can't do setresuid");
    }

    if (setresgid(egid, egid, -1) != 0) {
	perror("can't do setresgid");
    }
#endif
#endif
#endif

    if (execve(PERL, newargv, environ) == -1) {
	perror("cannot exec perl");
	exit(1);
    }
}
