#include <stdio.h>
#include <sys/file.h>
#include <fcntl.h>
#include <ctype.h>
#include <errno.h>
#include "inet.h"

#define CR		'\015'
#define LF		'\012'
#define EOM             ".\r\n"
#define EOM_LEN         3
#define CRLF            "\015\012"
#define SOCKBUF		4096
#define FALSE           0
#define TRUE            1

/* program to automatically add node to techinfo for the course evaluation
   guide S. Thorne */

int sock;
char            inbuf[SOCKBUF];

main(int argc, char **argv)
{
FILE   *fopen(), *crs_file;
char  *line, *title, *transline, *cp,*host,*port;
int  pnid = 27072;
int num,nid;


  if (argc < 2) {
    printf("need a filename of courses as input\n");
    exit(1);
    }
 /* open connection & id etc */
    host = "jimi";
    port = "9000";

    sock = inet_establish_connection(host, port, 0);
    if (sock < 0) {
	puts("Fatal error: could not establish connection.");
	exit(1);
    }
    get_msg(sock, inbuf, SOCKBUF);
printf("banner=%s\n",inbuf);
bzero(inbuf,sizeof(inbuf));
    send_msg(sock,"p:thorne:df",11); /* become a provider */
    get_msg(sock, inbuf, SOCKBUF);
printf("msg=<%s>\n",inbuf);
bzero(inbuf,sizeof(inbuf));
 

/* open course file and read each record */
  line = (char *) malloc(250);
  transline = (char *) malloc(250);

crs_file = fopen(argv[1],"r");

    while (fgets(line, 200, crs_file) != 0) {
      cp = (char *) index(line,'\n');
      *cp = '\0';
      cp = (char *) index(line,' ');
      if (cp){ 
	*cp = '\0';
	cp++;
      }
      title =  cp;
     /* add the node */
      sprintf(transline,"a:0:4:9:%s:%s %s:ceg:techinfodev:/mit/techinfodev/src/srv_ti/tmp/%s",
	      line,line,title,line);
      printf("<%s>\n",transline);
      send_msg(sock,transline,strlen(transline));
      get_msg(sock,inbuf,BUFSIZ);
      
      cp = (char *) index(inbuf,':');
      if (atoi(inbuf) != 0) {
	printf("<%s>/n",inbuf);
	continue;
      }
      
      if (cp)
	cp++;
      else
	continue;
      nid = atoi(cp);

      /* link the node */
      sprintf(transline,"l:%d:%d",pnid,nid);
      printf("<%s>",transline);
      send_msg(sock,transline,strlen(transline));
      get_msg(sock,inbuf,BUFSIZ);
     if (atoi(inbuf) != 0) {
	printf("<%s>/n",inbuf);
	continue;
      }
    }

fclose(crs_file);
close(sock);

}

get_msg(sock, buff, buffsize)	/* read message off socket */
    int             sock;
    char           *buff;
    int             buffsize;
{
    int             red;
    char           *cp,tempbuff[256];

*buff = '\0';   
while ((red = read(sock, tempbuff, buffsize)) > 0) {
  if (!strncmp(&tempbuff[red - 3], EOM, EOM_LEN)) {
    tempbuff[red-4] = '\0';
    strcat(buff,tempbuff); 
    if (strlen(buff) > 0)   
      break; }
  strncat(buff,tempbuff,red);
}
}

send_msg(tisock,str,len)
int tisock;
char *str;
int len;
{
int wrote;
char msg[SOCKBUF];

sprintf(msg,"%s%s",str,CRLF);
wrote = write(tisock,str,len + 2);
printf("wrote %d\n",wrote);
/* printf("wrote end %d\n",wrote); */
}











