#include <u.h>
#include <libc.h>

void
usage(void)
{
	fprint(2, "usage: timeout seconds command [arg ...]\n");
	exits("usage");
}

void
main(int argc, char *argv[])
{
	Waitmsg *w;
	long n;
	int cpid, tpid;
	char buf[4096];

	if(argc < 3)
		usage();

	if((n = strtol(argv[1], 0, 0)) == 0)
		usage();

	switch(cpid = fork()){
	case -1:
		sysfatal("fork: %r");
	case 0:
		/* see time.c */
		exec(argv[2], &argv[2]);
		if(argv[2][0] != '/' && strncmp(argv[2], "./", 2)
		&& strncmp(argv[2], "../", 3)){
			snprint(buf, sizeof(buf), "/bin/%s", argv[2]);
			exec(buf, &argv[2]);
		}
		sysfatal("%s: %r", argv[2]);
	}

	switch(tpid = fork()){
	case -1:
		sysfatal("fork: %r");
	case 0:
		sleep(n * 1000);
		exits("timeout");
	}

	if((w = wait()) == nil)
		sysfatal("wait: %r");

	if(w->pid == cpid)
		postnote(PNPROC, tpid, "die");
	else if(w->pid == tpid)
		postnote(PNPROC, cpid, "die");
	else
		assert(0);
	
	exits(w->msg);
}
