/**********************************************************************
 * luc_trn_file.c -- return filename of file containing transaction
 *
 * $Author: brlewis $
 * $Source: /afs/athena.mit.edu/astaff/project/lucydev/src/lib/RCS/luc_trn_file.c,v $
 * $Header: /afs/athena.mit.edu/astaff/project/lucydev/src/lib/RCS/luc_trn_file.c,v 1.2 91/09/24 14:37:40 brlewis Exp Locker: brlewis $
 *
 * Copyright 1991 by the Massachusetts Institute of Technology.
 *
 * For copying and distribution information, please see the file
 * <mit-copyright.h>.
 **********************************************************************/
#include <mit-copyright.h>

#ifndef lint
static char rcsid_luc_trn_file_c[] = "$Header: /afs/athena.mit.edu/astaff/project/lucydev/src/lib/RCS/luc_trn_file.c,v 1.2 91/09/24 14:37:40 brlewis Exp Locker: brlewis $";
#endif /* lint */

#include <stdio.h>
#include <strings.h>
#include <sys/errno.h>
#include <sys/file.h>
#include <lucy/lucy.h>
#include <lucy/memory.h>
tfile unix_tfile();             /* XXX should be in discuss .h file */

/**********************************************************************
 * luc_trn_file(lmeeting *mp, int n, char **f)
 *	caller sets mp (usually luv_curmtgp) to specify meeting
 *	caller sets n to specify transaction number
 *
 * - points *f at correct filename
 * - checks to see if file is already cached
 * - writes file to cache
 * - returns error code
 * Caller should call luc_free_file(f) when file is no longer needed.
 **********************************************************************/

long
luc_trn_file(mp, n, f)
     LMEETING *mp;
     int n;
     char **f;
{
  long code;
  char filename[128];
  int fd;
  tfile tf;

  /* Construct appropriate filename */
  sprintf(filename, "%s/%d", mp->dir, n);

  /* point *f at filename */
  if (!(*f = newstring(filename))) {
    luv_context[0] = '\0';	/* error context = "" */
    return((long) errno);
  }
  strcpy(*f, filename);

  /* If the file is already there, we're done. */
  if (!access(filename, R_OK))
    return(0L);

  /* if top-level directory isn't there, create it */
  if (access(luv_topdir, F_OK)) {
    if (mkdir(luv_topdir, 0700)) {
      sprintf(luv_context, "making directory `%s'", luv_topdir);
      return((long) errno);
    }
  }

  /* make meeting directory if it isn't there */
  if (access(mp->dir, F_OK)) {
    if (mkdir(mp->dir, 0700)) {
      sprintf(luv_context, "making directory `%s'", mp->dir);
      return((long) errno);
    }
  }

  /* get file from discuss */
  fd = open(filename, O_WRONLY|O_CREAT, 0666);
  if (fd < 0) {
    strcpy(luv_context, filename);
    return((long) errno);
  }
  tf = unix_tfile(fd);
  dsc_get_trn(&(mp->nb), n, tf, &code);
  if (code) {
    close(fd);
    unlink(filename);
    sprintf(luv_context, "%d", n);
    return(code);
  }

  if (close(fd) < 0) {
    code = (long) errno;
    strcpy(luv_context, filename);
    unlink(filename);
  }
  return(code);
}
