/**********************************************************************
 * Program to copy a TechInfo folder of documents into a directory
 * by Bruce Lewis
 *
 * $Author: brlewis $
 * $Source: /afs/net.mit.edu/dev/project/techinfodev/src/util/RCS/ticp.c,v $
 * $Header: /afs/net.mit.edu/dev/project/techinfodev/src/util/RCS/ticp.c,v 1.1 95/01/19 15:35:25 brlewis Exp $
 *
 * Copyright 1995 by the Massachusetts Institute of Technology.
 *
 * For copying and distribution information, please see the file
 * <mit-copyright.h>.
 **********************************************************************/
#include <mit-copyright.h>

static char rcsid[] = "$Header: /afs/net.mit.edu/dev/project/techinfodev/src/util/RCS/ticp.c,v 1.1 95/01/19 15:35:25 brlewis Exp $";

#define SA2TI_MAXENTRIES 255

#define ABORT { com_err("sa2ti", code, "(%s)", ti_context); exit(1); }
#define USAGEFMT "Usage: %s folderid [dirname]\n"
int quietf=0, recursef = 0;

#include <unistd.h>
#include <stdio.h>
#include <string.h>
#include <ti/ti.h>
#include <ti/node.h>
#include <ctype.h>

main(argc, argv)
     int argc;
     char *argv[];
{
  long code;
  char *server=NULL, *port=NULL;
  TI *tp;
  ti_node **tnodes;
  ti_menu *tmenu;
  int tnodecount, i, folder;
  FILE *fp;
  char *localfile;
  ti_recvinfo rcvinfo;

  /* make sure we have right # of args */
  if (argc < 2 || argc > 3 || !isdigit(argv[1][0]))
    {
      fprintf(stderr, USAGEFMT, argv[0]);
      exit(1);
    }

  folder=atoi(argv[1]);
  if (argc == 3) chdir(argv[2]);

  /* connect to the TechInfo server */
  if (code=ti_open(server, port, &tp)) ABORT;

  /* get TechInfo folder */
  if (code = ti_otl(tp, &tmenu, TI_BELOW, folder, 1)) ABORT;
  if (code = ti_rdmenu(tmenu, &tnodes, &tnodecount)) ABORT;
  if (tnodecount < 1)
    {
      fprintf(stderr, "sa2ti: No TechInfo folder with id %ld!\n", folder);
      exit(1);
    }

  /* receive files */
  for (i=1; i<tnodecount; i++)
    {
      if (ti_file(tnodes[i])[0])
	{
	  localfile=strrchr(ti_file(tnodes[i]), '/')+1;
	  if ((fp=fopen(localfile, "w")) == NULL)
	    {
	      perror(localfile);
	      exit(1);
	    }
	  ti_recvfile(tp, ti_id(tnodes[i]), 0, TI_ALL, fp, &rcvinfo);
	  if(fclose(fp) == EOF)
	    {
	      perror(localfile);
	      exit(1);
	    }
	}
    }

  /* done */
  ti_close(tp);
  exit(0);
}
