#include <sys/types.h>
#include <sys/socket.h>
#include <sys/un.h>

#include <netinet/in.h>
#include <arpa/inet.h>

#include <stdio.h>
#include <stdlib.h>
#include <strings.h>
#include <unistd.h>

#include <project2/include/Socket.h>
#include <project2/include/types.h>
#include <project2/include/route.h>

void usage(char *cmd) {
	printf("usage  : %s -n node <cmd> <addr> <iface> \n", cmd);
	printf("\n");
	printf("\t<cmd>       : add, del, chn");
	printf("\t <addr>     : destination IP address\n");
	printf("\t <iface>    : interface number on this router\n");
	printf("\nexample: %s -n 2 add 1.1.1.3 1 \n", cmd);
	exit(-1);
}

int
Main(int argc, char **argv)
{
	int s;
	int op = 0;
	char buf[1024];
	struct rt_msghdr *rtm = (struct rt_msghdr *) buf;

	if(argc != 4) {
		usage(argv[0]);
	} 
	if(!strcmp(argv[1],"add"))
		op = RTM_ADD;
	else if(!strcmp(argv[1], "del"))
		op = RTM_DELETE;
        else if(!strcmp(argv[1], "chn"))
	  op = RTM_CHANGE;
	else {
		usage(argv[0]);
	}

	if((s = Socket(AF_ROUTE, SOCK_RAW, 0)) < 0) {
		perror("Socket");
		exit(1);
	}

	bzero(rtm, sizeof(struct rt_msghdr));

	rtm->rtm_msglen = sizeof(struct rt_msghdr);
	rtm->rtm_type = op; 
	rtm->rtm_errno = 0;
	rtm->rtm_index = atoi(argv[3]);
	//rtm->rtm_label = atoi(argv[4]);

	rtm->rtm_dst.sin_family = AF_INET;
	rtm->rtm_dst.sin_port = 0;
	rtm->rtm_dst.sin_addr.s_addr = inet_addr(argv[2]);

	if(Write(s, (caddr_t) rtm, rtm->rtm_msglen) <0) {
		perror("Write");
		exit(1);
	}

	if(Close(s) < 0) {
		perror("Close");
		exit(1);
	}

	return 0;
}
