/* $Id: report.c,v 1.1 1999/08/23 16:18:39 naamato Exp $ */
/*
 * Copyright(c) 1998 by Hitachi.Ltd All rights reserved.
 *
 */

#include <stdio.h>
#include <stdlib.h>
#include <sys/types.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <signal.h>
#include "dvmrp_def.h"

void parse_file();
void timer();

#define IF_NAME_SIZE 8

char usage[] = "Usage: report [-i interface] [-s src_addr] [-d dst_addr] [-f file] [-C count] -p prefix -n num\n";
int time_expire;

main(argc, argv)
int argc;
char **argv;
{
    char opt;
    extern char *optarg;
    u_long ifaddr;
    u_long src,dst;
    u_long net,mask;
    char *if_name;
    char flags;
    int net_num;
    FILE *fp; 
    int count;
#ifndef SOLARIS
    struct sigvec sigv;
#endif

    dst = 0;
    net = src = 0;
    dvmrp_init();
    net_num = 0;
    fp=NULL;
    count=1;

    while((opt = getopt(argc,argv,"i:p:n:s:d:f:C:")) != -1) {
        switch(opt) {
	case 'i' : if_name=malloc(IF_NAME_SIZE);
	           strcpy(if_name,optarg);
	           break;
	case 'n' : net_num = atoi(optarg);
	           break;
	case 'p' : prefix_parse(optarg,&net,&mask);
	           break;
	case 's' : src = inet_stoa(optarg);
	           break;
	case 'd' : dst = inet_stoa(optarg);
	           break;
	case 'f' : if(!(fp=fopen(optarg,"r"))) 
		      printf(" %s open error \n",optarg);
		   break;
	case 'C' : count = atoi(optarg);
	           break;
	default:   fprintf(stderr,usage);
	           break;
	}
    }

    if(!net && !fp) {
        fprintf(stderr,usage);
	exit(1);
    }
    
    interface_init();

    if(net_num) build_net_list(net,mask,net_num);
    if(fp) parse_file(fp);

#ifdef SOLARIS
    sighold(SIGALRM);
    sigset(SIGALRM,timer);
#else
    bzero((char *)&sigv, sizeof(sigv));
    sigv.sv_flags = 0;
    sigv.sv_handler = timer;
    sigv.sv_mask = 0;
    sigvec(SIGALRM, &sigv, (struct sigvec *)NULL);
#endif

    time_expire = 1;
    dvmrp_report_send(if_name,src,dst);
    for(;count>1;count--) {
	sleep(DVMRP_REPORT_INTERVAL);
	dvmrp_report_send(if_name,src,dst);
    }

    if(fp) fclose(fp);
}


void parse_file(fp)
FILE *fp;
{
    char c,buf[256],*bufp;
    u_long net,mask;
    int metric;

    bufp = buf;
    while((c=getc(fp)) != EOF) {
        if(c == 0x0a) {
	    *bufp = '\0';
	    metric = atoi(buf);
	    add_network_list2(NULL,net,mask,metric);
	    bzero(buf,256);
	    bufp = buf;
	}
	else if(c == ' ' || c == '\t') {
	    *bufp = '\0';
	    prefix_parse(buf,&net,&mask);
	    bzero(buf,256);
	    bufp = buf;
	}
	else {
	    *bufp++ = c;
	}
    }
	
}

void timer()
{
    time_expire = 1;
}
