/* Program to cause gateways to reboot or restart. */

/*
 *------------------------------------------------------------------
 *
 * $Source: /afs/net.mit.edu/tools/src/gwrst/RCS/gwrst.c,v $
 * $Revision: 1.1 $
 * $Date: 90/03/02 13:46:42 $
 * $State: Exp $
 * $Author: tom $
 * $Locker:  $
 *
 * $Log:	gwrst.c,v $
 * Revision 1.1  90/03/02  13:46:42  tom
 * Initial revision
 * 
 * Revision 1.2  87/06/04  18:30:54  jon
 * Prompts for password if only given one argument (host).
 * 
 *------------------------------------------------------------------
 */

#ifndef lint
static char *rcsid_statd_c = "$Header: /afs/net.mit.edu/tools/src/gwrst/RCS/gwrst.c,v 1.1 90/03/02 13:46:42 tom Exp $";
#endif	lint

#include	<stdio.h>
#include	<sys/types.h>
#include	<sys/socket.h>
#include	<netinet/in.h>
#include        <arpa/inet.h>
#include	<netdb.h>
#include	<signal.h>
#include	<errno.h>
#include	<setjmp.h>
/* #include	<sys/time.h> */

#define GW_CONTROL htons(88)
#define REBOOT 1

extern	int errno;

main(argc, argv)
int	argc;
char	**argv;
{
    int			f, cc, request;
    char		recvbuf[576];
    struct sockaddr_in	sin;
    u_long		host, gethst();
    char                *getpass(), *password;

    if (argc == 4) {
	host = gethst(argv[1]);
	password = argv[2];
	request = atoi(argv[3]);
    }
    else if (argc == 3) {
	host = gethst(argv[1]);
	password = argv[2];
	request = REBOOT;
    }
    else if (argc == 2) {
      host = gethst(argv[1]);
      request = REBOOT;
      password = getpass ("Password:");
    }
    else
      usage(argv[0]);
    
    f = socket(AF_INET, SOCK_DGRAM, 0);
    if (f < 0) {
	perror("gwstat: socket");
	exit(3);
    }
    bzero((char *)&sin, sizeof (sin));
    sin.sin_family = AF_INET;
    sin.sin_port = GW_CONTROL;
    if (bind(f, &sin, sizeof (sin)) < 0) {
	perror("gwstat: bind");
	exit(1);
    }

    /* send out a request */
    recvbuf[0] = 0;
    recvbuf[1] = 0;
    recvbuf[2] = 0;
    recvbuf[3] = request;
    strcpy(&recvbuf[4], password);
    sin.sin_family = AF_INET;
    sin.sin_port = GW_CONTROL;
    sin.sin_addr = *(struct in_addr *)(&host);
    printf("sending request %d to %s\n",
	   request, inet_ntoa(host));
    cc = sendto(f, &recvbuf[0], 5+strlen(password), 0, &sin, sizeof(sin));
    if (cc < 0) {
	perror("gwstat: sendto");
	exit(1);
    }
}


usage(name)
char	*name;
{
    fprintf(stderr, "usage: %s host passwd [command]\n", name);
    exit(1);
}

u_long	gethst(hst)
char	*hst;
{
    struct hostent	*hstent;
    u_long		host;

    if ((*hst < '0') || (*hst > '9')) {
	if ((hstent = gethostbyname(hst)) == NULL) {
	    fprintf(stderr, "Don't know host %s\n", hst);
	    exit(1);
	}
	printf ("gethostbyname returns host = %s, %s, %s\n", hstent->h_name,
		inet_ntoa(*(u_long *)hstent->h_addr), inet_ntoa(*(u_long *)hstent->h_addr_list[0]));
	return(*(u_long *)(hstent->h_addr));
    } else {
	if ((host = inet_addr(hst)) == NULL) {
	    fprintf(stderr, "Don't know address %s\n", hst);
	    exit(1);
	}
	return(host);
    }
}
