/*	call prog argv ...
*
* This is a generic "wrapper" program that  surrounds  other  programs
* and does some useful things before execing them.
*
* If prog differs from argv[0], we engage in a bit of Unix wizardry to
* make  programs  like  top  and  ps show argv[0] rather than the prog
* name.  This is so that top and ps listing won't show a lot of  "csh"
* or  "perl"  processes,  but  will  display  the  name of the script.
* [Unfortunately, this doesn't work with top.]
*/
:1#include "V.h"

char *tmpdir = "/tmp";

main(ac,av,ev)
	char **av, **ev;
{	int  a, i, n;
	char **argv;
	char **envv;
	char *name=0;
	char *prog=0;
	char *nbuf=0;

:1	ac = Vinit(ac,av);

	av[ac] = 0;		/* Paranoia */

	if (Vlvl > 2)
		for (a=0; a<ac; a++)
:3			V3 "Arg[%2d]=\"%s\"",a,av[a] D;

	if (ac < 1) {
		fprintf(stderr,"Usage: $s prog argv ...\n",av[0]);
		Fail;
	}
	prog = av[1];
	argv = av + 2;
	envv = ev;
	if (ac > 1) {
		if (strcmp(av[1],av[2])) {	/* prog and argv[0] differ */
			name = Lastfld('/',av[2]);
:3			V3 "name=\"%s\"",name D;
			n = strlen(tmpdir) + strlen(name) + 2;
			if (!(nbuf = (char*)Malloc(n)))
				Fail;
			sprintf(nbuf,"%s/%s",tmpdir,name);
:3			V3 "symlink(\"%s\",\"%s\") ...",av[1],nbuf D;
			if (symlink(av[1],nbuf) < 0) {
				switch(errno) {
				case EEXIST:
:4					V4 "Unlink old \"%s\"",nbuf D;
					if (unlink(nbuf) < 0) {
:1						P1 "Can't unlink \"%s\" [Err %d=%s]",nbuf,Erreason D;
						Fail;
					}
:4					V4 "symlink(\"%s\",\"%s\") ...",av[1],nbuf D;
					if (symlink(av[1],nbuf) == 0)
						break;
				default:
:1					P1 "Can't create symlink \"%s\" [Err %d=%s]",nbuf,Erreason D;
					Fail;
				}
				/*NOTREACHED*/
			}
:5			V5 "Symlink \"%s\" should exist now.",nbuf D;
			prog = nbuf;

		}
	}
	Execve(prog,argv,envv);
fail:
	Exit(1);
}
