/**********************************************************************
 * document viewing module
 *
 * $Author: warlord $
 * $Source: /afs/sipb.mit.edu/project/sipb-athena/repository/src/olh/libmenu/viewer.c,v $
 * $Header: /afs/sipb.mit.edu/project/sipb-athena/repository/src/olh/libmenu/viewer.c,v 1.3 1996/03/18 15:42:03 warlord Exp $
 *
 * Copyright (c) 1990, Massachusetts Institute of Technology
 **********************************************************************/

#ifndef lint
#ifndef SABER
static char rcsid_viewer_c[] = "$Header: /afs/sipb.mit.edu/project/sipb-athena/repository/src/olh/libmenu/viewer.c,v 1.3 1996/03/18 15:42:03 warlord Exp $";
#endif
#endif

#include <stdio.h>
#include <errno.h>
#include <strings.h>
#include <memory.h>
#include <menu.h>
#include <sys/file.h>
#include <unistd.h>

/****************************************************************
 * viewdoc
 ****************************************************************/

long
viewdoc(e, device, prefix)
     MenuEntry *e;
     char *device;
     char *prefix;
{
  char call[1024], pointer[64], *filsys, *s, *filename, *viewer;
  MenuEntry *e2;
  long code;
  int i;

  /* Find file format */
  strcpy(pointer, "viewer:");	/* XXX move to header file */
  s = field_value(e, FILE_FORMAT);
#ifdef LOG_USAGE
  log_view(field_value(e,FILE_LOCATION));
#endif
  if (*s == '\0') s = "plain_text";
  strcat(pointer, s);

  code = pointerEntry(pointer, &e2);
  if (code) return(code);

  /* attach filesystems */
  filename = field_value(e, FILE_LOCATION);
  if (*filename == '\0') return(ERR_MENU_NOFIL);
  /* Plugging a security hole:  Under no circumstances should
   * a file location contain backquotes, allowing arbitrary
   * shell commands to be run, when an entry looks like an ordinary
   * document.
   */
  if (index(filename, '`')) return(ERR_MENU_INVALFIL);
  filsys = field_value(e, FILESYSTEM);
  if (*filsys) {
    if (access(filename, F_OK)) {
      code = olh_attach(filsys, 0);
      if (code) return(code);
    }
  }

  viewer = field_value(e2, device);
  if (*viewer == '\0') return(ERR_MENU_NOVIEWER);
  filsys = field_value(e2, FILESYSTEM);
  if (*filsys) {
    if (access(filename, F_OK)) {
      code = olh_attach(filsys, 0);
      if (code) return(code);
    }
  }

  /* System call to sh */
  if (prefix != NULL)
    sprintf(call,"%s; file=%s; %s", prefix, filename, viewer);
  else
    sprintf(call,"file=%s; %s", filename, viewer);

  i = system(call) >> 8;	/* shift 8 bits to get return status */
  switch(i) {
  case 0:
    return(0L);
  case 127:
    return(ERR_MENU_NOSHELL);
  default:
    return(ERR_MENU_VIEWERFAILED);
  }
}
