/*
 * CDDL HEADER START
 *
 * The contents of this file are subject to the terms of the
 * Common Development and Distribution License, Version 1.0 only
 * (the "License").  You may not use this file except in compliance
 * with the License.
 *
 * You can obtain a copy of the license at usr/src/OPENSOLARIS.LICENSE
 * or http://www.opensolaris.org/os/licensing.
 * See the License for the specific language governing permissions
 * and limitations under the License.
 *
 * When distributing Covered Code, include this CDDL HEADER in each
 * file and include the License file at usr/src/OPENSOLARIS.LICENSE.
 * If applicable, add the following below this CDDL HEADER, with the
 * fields enclosed by brackets "[]" replaced with your own identifying
 * information: Portions Copyright [yyyy] [name of copyright owner]
 *
 * CDDL HEADER END
 */
/*
 * Copyright 2003 Sun Microsystems, Inc.  All rights reserved.
 * Use is subject to license terms.
 */

#pragma ident	"%Z%%M%	%I%	%E% SMI"

#include <stdio.h>
#include <stdlib.h>
#include <unistd.h>
#include <fcntl.h>
#include <string.h>
#include <errno.h>
#include <sys/types.h>
#include <signal.h>
#include <libproc.h>

static	int	start(char *);

static	char	*command;

int
main(int argc, char **argv)
{
	int rc = 0;

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

	if (argc <= 1) {
		(void) fprintf(stderr, "usage:\t%s pid ...\n", command);
		(void) fprintf(stderr, "  (set stopped processes running)\n");
		return (2);
	}

	while (--argc > 0)
		rc += start(*++argv);

	return (rc);
}

static int
start(char *arg)
{
	struct ps_prochandle *P;
	int gcode;

	if ((P = proc_arg_grab(arg, PR_ARG_PIDS,
	    PGRAB_FORCE | PGRAB_RETAIN | PGRAB_NOSTOP, &gcode)) == NULL) {
		(void) fprintf(stderr, "%s: cannot control %s: %s\n",
			command, arg, Pgrab_error(gcode));
		return (1);
	}

	/*
	 * If the victim is stopped because of a job control signal, we
	 * need to send it SIGCONT to get it moving again, otherwise
	 * the agent will not be able to run, and so will not be able to
	 * exit the process.
	 */
	(void) kill(Pstatus(P)->pr_pid, SIGCONT);

	/*
	 * if the agent already exists, Pcreate_agent will adopt the
	 * extant agent so that we can destroy it
	 */
	if (Pstatus(P)->pr_lwp.pr_flags & PR_AGENT) {
		if (Pcreate_agent(P) != 0) {
			(void) fprintf(stderr,
			    "%s: cannot remove agent from %s: %s\n",
			    command, arg, strerror(errno));

			Prelease(P, 0);
			return (1);
		}

		Pdestroy_agent(P);
	}

	/*
	 * Prelease could change the tracing flags or leave the victim hung
	 * so we set the process running and free the handle by hand.
	 */
	(void) Psetrun(P, 0, 0);
	Pfree(P);

	return (0);
}