/*
 * $Id: ipxroute.c,v 1.1 1995/01/05 09:14:58 root Exp $
 *
 * IPX Route
 *	Manipulates IPX routing tables
 */
#include "ipxroute.h"

int skfd = 0;
#define _PATH_PROCNET_IPXROUTE	"/proc/net/ipx_route"

/*
 * Dump routing information
 */
static void ipxrt_print(void) {
  FILE *fp = fopen(_PATH_PROCNET_IPXROUTE,"r");
  int ch;
  while ((ch = getc(fp)) != EOF) putchar(ch);
  fclose(fp);
}

/*
 * Dump usage
 */
static void usage(void) {
  fprintf(stderr,"Usage: ipxroute\n");
  fprintf(stderr,"Usage: ipxroute add {-frametype} iface network  [router]\n");
  fprintf(stderr,"Usage: ipxroute del {-frametype} iface network  [router]\n");
  fprintf(stderr,"\nAvailable frame types:\n\tethernet_ii, 802.2, snap, 802.3\n");
  fprintf(stderr,"Routers are specified:\n\tnetwork:node\n");
  exit(-1);
}

void rt_fill_def(struct ipx_route_def *rt,char **args) {
  rt->ipx_flags = 0;
  if (**args == '-') {
    rt->ipx_flags = asc2frame(&args[0][1]);
    args++;
  }
  if (!*args) usage();
  strncpy(rt->ipx_device,*args++,15);
  rt->ipx_device[15] = '\000'; /* Make sure we are null terminated */
  if (!*args) usage();
  rt->ipx_network = htonl(gethex(*args++));

  if (*args) {
    rt->ipx_flags |= IPX_RT_ROUTED;
    rt->ipx_router_network = htonl(ipx_getipxaddr(rt->ipx_router_node,*args));
  }
  else {
    rt->ipx_router_network = IPX_ROUTE_NO_ROUTER;
    memset(rt->ipx_router_node,0,sizeof rt->ipx_router_node);
  }
}

/*
 * Add a routing table entry
 */
int ipxrt_add(char **args) {
  struct ipx_route_def rt;
  rt_fill_def(&rt,args);
  if (ioctl(skfd,SIOCADDRT,&rt) < 0) {
    perror("ipxroute-add");
    return -1;
  }
  return 0;
}

int ipxrt_del(char **args) {
  struct ipx_route_def rt;
  rt_fill_def(&rt,args);
  if (ioctl(skfd,SIOCDELRT,&rt) < 0) {
    perror("ipxroute-del");
    return -1;
  }
  return 0;
}


int main(int  argc, char **argv) {
  int i;

  if (*++argv == NULL) {
    ipxrt_print();
    exit(0);
  }

  /* Fetch the command. */
  if (strcmp(*argv,"add") && strcmp(*argv,"del")) usage();

  if ((skfd = socket(AF_IPX,SOCK_DGRAM,0))<0) {
    perror("socket");
    exit(-1);
  }

  if (!strcmp(*argv,"add"))
    i = ipxrt_add(++argv);
  else
    i = ipxrt_del(++argv);
  return i;
}
