/*
 * Copyright 2001, 2002, 2003 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 <unistd.h>
#include <stdlib.h>
#include <errno.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <time.h>
#include "svstat.h"
#include "iolib.h"
#include "freedt.h"
#include "config.h"
const char *progname = "svstat";
const char *proghelp =
	"Usage: svstat [OPTIONS] servicedir [servicedir ...]\n"
	"Show information about supervised services.\n\n";

#define FAIL(msg) { \
	format(fd_out, "@c\n", msg); \
	continue; \
	}

int main(int argc, char **argv) {
	int fd, i, cwd;

	get_default_args(argc, argv);

	cwd = open(".", O_RDONLY);
	if (cwd < 0) die("unable to open current directory");
		
	for (i = optind; i < argc; i++) {
		struct svstat s;
		int rc;
		long tup;

		format(fd_out, "@c: ", argv[i]);

		if (fchdir(cwd) < 0)
			FAIL("unable to chdir to original dir");
		if (chdir(argv[i]) < 0)
			FAIL("unable to chdir to service dir");

		fd = open("supervise/status", O_RDONLY);
		if (fd < 0) {
			FAIL("unable to open supervise/status");
		}
		rc = read(fd, &s, sizeof s);
		close(fd);
		if (rc < 0)
			FAIL("unable to read supervise/status");

		tup = time(NULL) - s.starttime;

		if (s.up) {
			format(fd_out, "up (pid @i) @l seconds\n",
				s.pid, tup);
		} else {
			const char *updown = "up";
			fd = open("down", O_RDONLY);
			if (fd >= 0) {
				close(fd);
				updown = "down";
			}
			format(fd_out, "down @l seconds, normally @c\n",
				tup, updown);
		}
	}

	close(cwd);

	return 0;
}

