/*
 * This file is part of the OLH system.
 * It is used to show the information on a node
 *
 *      Lucien Van Elsen
 *      MIT Project Athena
 *
 * Copyright (C) 1990 by the Massachusetts Institute of Technology.
 * For copying and distribution information, see the file "mit-copyright.h".
 *
 *      $Source: /afs/sipb.mit.edu/project/sipb-athena/repository/src/olh/ascii/copy.c,v $
 *      $Id: copy.c,v 1.2 1993/05/03 14:03:29 miki Exp $
 *      $Author: miki $
 */

#include <sys/errno.h>
#include <sys/file.h>
#include <sys/param.h>
#include <sys/wait.h>
#ifdef SYSV
#include <sys/fcntl.h>
#endif
#include <olh.h>

void
copy_module()
{
  MenuEntry *e;
  char buffer[MAXPATHLEN],*homedir,*p,*filename;
  char dest_file[MAXPATHLEN];
  char new_file[MAXPATHLEN];
  char new_prompt[MAXPATHLEN];
  char err_msg[80];
  char ch;
  int pid,fd;
#ifdef SYSV
  int status;
#else
  union wait status;
#endif

  if (current[current_menu] == 0) {
    sprintf(buffer,"Please select an item first.");
    OLH_ui_message(buffer);
    return;
  }

  e = nth_entry(menu[current_menu],current[current_menu]);

  if (is_menu(e)) {
    sprintf(buffer,"You cannnot copy a menu.  Please select a document instead and try again.");
    OLH_ui_message(buffer);
    return;
  }

  homedir = getenv("HOME");
  if (homedir == NULL)
    homedir = "/tmp";

  /* Get last part of actual file name */
  filename = (field_value(e, FILE_LOCATION));
  p = rindex(filename,'/');
  if (p == NULL)
    p = filename;
  else
    p = p+1;

  sprintf(dest_file,"%s/%s",homedir,p);
  sprintf(buffer,"Default: %s",dest_file);
  sprintf(new_prompt,"Copy \"%s\" to: ",field_value(e,NODE_LABEL));

  while(1) {
    current_prompt = new_prompt;
    OLH_ui_message(buffer);
    paint_prompt();
    wrefresh(win_prompt);

    echo();
    if (wgetstr(win_prompt,new_file) == OK) {
      if (new_file[0] == '\0')
	strcpy(new_file,dest_file);
      fd = open(new_file,O_WRONLY|O_TRUNC|O_CREAT,0666);
      if (fd < 0) {
	sprintf(err_msg,"Error: %s; press any key to continue",
		sys_errlist[errno]);
	OLH_ui_message(err_msg);
	noecho();
	ch = wgetch(win_prompt);
	continue;
      }
      else {
	close(fd);
	break;
      }
    }
  }

  noecho();

  if ((pid = vfork()) == -1) {
    sprintf(err_msg,"Could not fork to copy: %s", sys_errlist[errno]);
    return;
  }

  if (pid == 0) {
    /* child */
    execl("/bin/cp","cp",filename,new_file,NULL);
    perror("copy: execl /bin/cp");
    _exit(-1);
  }
  else
    while (wait(&status) != pid)
      ;

#ifdef SYSV
  if (WEXITSTATUS(status) == 0)
#else
  if (status.w_retcode == 0)
#endif
    OLH_ui_message("Copy successful.");
  else
    OLH_ui_message("Error in copy");
}
