/* alive.c -  client for sending information about a host 
   Copyright (C) 2003, Kris Foster <kris@krweb.net>

   This program is free software; you can redistribute it and/or modify
   it under the terms of the GNU General Public License as published by
   the Free Software Foundation; either version 2 of the License, or
   (at your option) any later version.

   This program is distributed in the hope that it will be useful,
   but WITHOUT ANY WARRANTY; without even the implied warranty of
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   GNU General Public License for more details.

   You should have received a copy of the GNU General Public License
   along with this program; if not, write to the Free Software
   Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
*/

#include <errno.h>
#include <netdb.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <arpa/inet.h>
#include <netinet/in.h>
#include <sys/types.h>
#include <sys/socket.h>
#include "alived.h"

void pversion(void);
void usage(void);
void daemonize(void);

int 
main(int argc, char *argv[])
{
	int sockfd;
	int nbytes;
        int a_len, m_len;
        int server_port=ALIVE_PORT;
        char *server_address="127.0.0.1";
	struct sockaddr_in serv_addr;
	struct hostent *he;
        struct message dgram;
        
        a_len=sizeof(struct sockaddr);
        m_len=sizeof(struct message);

	if(argc<2) {
		usage();
		exit(1);
	}

        // Build the payload for sending to the server
	dgram.type=htonl(KEEPALIVE);
	strcpy(dgram.id,argv[1]);
	
        // Build the header of the packet
	if(argc==3) {
		server_address=argv[2];
        }
        he=gethostbyname(server_address);
        if(he==NULL) {
                perror("gethostbyname");
                exit(1);
	}
	sockfd=socket(AF_INET, SOCK_DGRAM, 0);
        if(sockfd==-1) {
		perror("socket");
		exit(1);
	}
	serv_addr.sin_family=AF_INET;
	if(argc==4) {
		server_port=atoi(argv[3]);
	}
        serv_addr.sin_port=htons(server_port);
	serv_addr.sin_addr = *((struct in_addr *)he->h_addr);
	memset(&(serv_addr.sin_zero), '\0', 8);
	
        // For now, run once and exit.
        // In a future version I'll add support to specify how many times
        // how often, etc.  The user can put this in a cron job or something
        nbytes=sendto(sockfd,&dgram,m_len,0,(struct sockaddr *)&serv_addr,a_len);
        if(nbytes==-1) {
                perror("sendto");
                exit(1);
        }

	close(sockfd);

	return 0;
}

void 
pversion(void)
{
        printf("alive version %s\n", VERSION);
}

void 
usage(void)
{
	printf("Usage: alive hostname [server_address] [port]\n");
}

void 
daemonize(void)
{
        pid_t pid;

        pid=fork();

        if(pid==-1) {			// Oops
                perror("fork");
                exit(-1);
        }
        else if(pid!=0)			// We're the parent so lets exit
                exit(0);
}

