/*
 * Copyright 2001, 2002, 2003, 2013 Adam Sampson <ats@offog.org>
 *
 * Permission to use, copy, modify, and/or distribute this software for any
 * purpose with or without fee is hereby granted, provided that the above
 * copyright notice and this permission notice appear in all copies.
 *
 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
 */

#include <pwd.h>
#include <sys/types.h>
#include <unistd.h>
#include <stdlib.h>
#include "iolib.h"
#include "freedt.h"
#include "config.h"
const char *progname = "envuidgid";
const char *proghelp =
	"Usage: envuidgid [OPTIONS] account command ...\n"
	"Run a command with $UID and $GID set for an account.\n\n";

int main(int argc, char **argv) {
	struct passwd *p;
	buffer b = BUFFER;

	get_default_args(argc, argv);
	if ((argc - optind) < 2)
		help();

	p = getpwnam(argv[optind]);
	if (!p)
		die2(argv[optind], "no such account");
	bformat(&b, "@i", p->pw_uid);
	if (setenv("UID", bstr(&b), 1) < 0)
		die("unable to set UID");
	bfree(&b);
	bformat(&b, "@i", p->pw_gid);
	if (setenv("GID", bstr(&b), 1) < 0)
		die("unable to set GID");
	bfree(&b);

	++optind;
	execvp(argv[optind], &argv[optind]);
	die2(argv[optind], "unable to exec");

	return 0; /* NOTREACHED */
}

