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

#include <stdio.h>
#include <stdlib.h>
#include <signal.h>
#include <sys/types.h>
#include "pim_def.h"

#define IF_NAME_SIZE  8

void parse_file();
void timer();

char usage[] = "Usage: bstrap [-i interface] [-s src_addr] [-d dst_addr] [-h hashmask] [-p priority] [-f list ] [-C count] -b bsr_addr\n";

int time_expire;

main(argc, argv)
int argc;
char **argv;
{
    char opt;
    extern char *optarg;
    u_long src,dst,bsr;
    u_int hashmask,pri;
    FILE *fp;
    char *if_name;
    int count;
#ifndef SOLARIS
    struct sigvec sigv;
#endif

    src = dst = bsr = 0;
    if_name = NULL;
    fp = NULL;
    count = 1;

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

    if(!bsr) {
        fprintf(stderr,usage);
	exit(1);
    }

    interface_init();

    pim_init();
    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;
    while(count) {
        if(time_expire) {
	    pimsm_bsr_send(if_name,src,dst,bsr,pri);
            time_expire = 0;
            count--;
            alarm(PIM_BOOTSTRAP_PERIOD);
        }
    }
}

void parse_file(fp)
FILE *fp;
{
    char c,buf[256],*bufp;
    u_long grp,mask,rp_addr;
    int holdtime;
    int pri;

    bufp = buf;
    grp = mask = rp_addr = 0;
    pri = holdtime = 0;
    while((c=getc(fp)) != EOF) {
        if(c == 0x0a) {
	    *bufp = '\0';
	    pri = atoi(buf);
	    bzero(buf,256);
	    bufp = buf;
	    add_rpset_list2(0,grp,mask,rp_addr,(u_short)holdtime,(u_short)pri);
	    grp = mask = rp_addr = 0;
	}
	else if(c == ' ' || c == '\t') {
	    *bufp = '\0';
	    if(!grp) {
	      prefix_parse(buf,&grp,&mask);
	    }
	    else if(!rp_addr){
	      rp_addr = inet_stoa(buf);
	    }
	    else {
		holdtime = atoi(buf);
	    }
	    bzero(buf,256);
	    bufp = buf;
	}
	else {
	    *bufp++ = c;
	}
    }
	
}

void timer()
{
    time_expire = 1;
}
