/* 
 * $Id: run_setid_script.c,v 1.1 1994/09/22 17:39:18 ejb Exp $
 * $Source: /home/ejb/source/util/work/RCS/run_setid_script.c,v $
 * $Author: ejb $
 *
 */

#ifndef NO_RCS_HDRS
/* Define a static function and call it.  No warnings this way. */
static void rcsid(char *s)
{rcsid("@(#)$Id: run_setid_script.c,v 1.1 1994/09/22 17:39:18 ejb Exp $");s=s;}
#endif /* ! NO_RCS_HDRS */

#ifndef CMD
#error "Must define CMD to the command to run"
#endif

#if (!defined(UID) && !defined(GID))
#error "Must define at least one of UID or GID to the uid or gid to run as"
#endif

#ifndef UID
#define UID -1
#endif

#ifndef GID
#define GID -1
#endif

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

static char *whoami;

int main(int argc, char *argv[])
{
    char *t = CMD;

    if ((whoami = strrchr(argv[0], '/')) == NULL)
	whoami = argv[0];
    else
	whoami++;

    if (t[0] != '/')
    {
	fprintf(stderr, "%s: CMD must be an absolute path (not %s)\n",
		whoami, CMD);
	exit(1);
    }

    if (GID != -1)
    {
	if (setgid(GID) == -1)
	{
	    fprintf(stderr, "%s: setgid(%d) failed: ", whoami, GID);
	    perror(NULL);
	    exit(1);
	}
    }

    if (UID != -1)
    {
	if (setuid(UID) == -1)
	{
	    fprintf(stderr, "%s: setuid(%d) failed: ", whoami, UID);
	    perror(NULL);
	    exit(1);
	}
    }

    /* Execute the command giving it us as argv[0] */
    execv(CMD, argv);
    fprintf(stderr, "%s: exec %s FAILED: ", whoami, CMD);
    perror(NULL);
    exit(-1);
}
