#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <stdlib.h>
#include <stdio.h>
#include <netdb.h>
#include <string.h>

static char Rcsid[] = "$Header: /jayar/i/tm4/tmu/src/tmumon/RCS/tm.c,v 1.3 2011/01/13 20:47:51 drg Exp $";

char TMhost[256];

/* This should come from getservbyname, but it is too hard to make that work
 * from a unprivileged program. -- drg
 */
#define TMPORT_HOUSEKEEPING	3462

main(argc, argv)
	int argc;
	char *argv[];
	{
	int sock, i, usestdin;
	struct sockaddr_in serveraddr;
	struct hostent *hp, *gethostbyname();
	FILE *server;
	char buf[1024], *host;

	if((host = getenv("TM_SERVER")) != (char *) NULL)
		strncpy(TMhost, host, sizeof(TMhost) - 1);
	else
		strcpy(TMhost, DEFAULT_SERVER);

	while((argc > 1) && (argv[1][0] == '-') && (argv[1][1] != '\0')) {
		switch(argv[1][1]) {
		case 'h':
			if(!argv[2])
				usage();
			strncpy(TMhost, argv[2], sizeof(TMhost));
			--argc;
			argv++;
			break;

		default:
			usage();
			}
		argv++;
		--argc;
		}

	if(argc < 2)
		usage();
	sock = socket(AF_INET, SOCK_STREAM, 0);
	if(sock < 0) {
		perror("opening stream socket");
		exit(1);
		}
	serveraddr.sin_family = AF_INET;
	hp = gethostbyname(TMhost);
	if(hp == (struct hostent *) NULL) {
		fprintf(stderr, "scan: can't find address for '%s'\n", TMhost);
		exit(1);
		}
	bcopy(hp->h_addr, &serveraddr.sin_addr.s_addr, sizeof(serveraddr.sin_addr.s_addr));
	serveraddr.sin_port = htons(TMPORT_HOUSEKEEPING);

	if(connect(sock, (struct sockaddr *) &serveraddr, sizeof(serveraddr))) {
		perror("can't connect to tmumon");
		exit(1);
		}

	server = fdopen(sock, "r");

	if((argc == 2) && !strcmp(argv[1], "-"))
		usestdin = 1;
	else
		usestdin = 0;

	while(1) {
		if(usestdin) {
			if(fgets(buf, sizeof(buf), stdin) == NULL)
				break;
			write(sock, buf, strlen(buf));
			}
		else	{
			buf[0] = '\0';
			for(i=1; i<argc; i++) {
				strncat(buf, argv[i], sizeof(buf) - strlen(buf));
				strncat(buf, " ", sizeof(buf) - strlen(buf));
				}
			strncat(buf, "\n", sizeof(buf) - strlen(buf));
			write(sock, buf, strlen(buf));
			}
		while(1) {
			buf[0] = '\0';
			if(!fgets(buf, sizeof(buf), server)) {
				exit(1);
			}
			if(strlen(buf) <= 1)
				break;
			if(feof(server) || ferror(server)) {
				exit(1);
				}
			fputs(buf, stdout);
			fflush(stdout);
			}
		if(!usestdin)
			break;
		}
	exit(0);
	}



usage() {
	fprintf(stderr, "usage: tm [-h hostname] command; or tm -\n");
	exit(1);
	}
