/*
 * ftp.c : Fetches a file by anonymous ftp.
 *
 * George Ferguson, ferguson@cs.rochester.edu, 12 Nov 1991.
 *
 * This is just an initial cut at providing the real kind of ftp
 * services that we want. In particular, we will eventually be using
 * Prospero for the transfers, rather than feeding commands to ftp.
 * Also, it would be nice to be able to log in from xarchie as well
 * as fetching files immediately.
 *
 * The Settings panel now allows the transfer type and local directory
 * to be set for ftp transfers. We're getting there...
 *
 * Note that error messages form ftp go to stderr, and the return status
 * signalled by pclose() is really inadequate. It is almost always 0,
 * and so "file not found" errors go unnoticed but for the stderr message.
 *
 * This code contains definite Unix-isms. If if won't compile for you,
 * you'll have to do without the ftp capability or hack the code
 * yourself.
 *
 */
#include <stdio.h>
#include <pwd.h>
#include <X11/Intrinsic.h>
#include "appres.h"
extern char *getenv();

#define FTP_CMD "/usr/ucb/ftp -n"

void
ftp(host,loc,file)
char *host,*loc,*file;
{
    FILE *fp;
    struct passwd *pwe;
    char *username,hostname[64];
    int status;

    if ((pwe=getpwuid(getuid())) != NULL)
	username = pwe->pw_name;
    else if ((username=getenv("USER")) == NULL)
	username = "xarchie_user";
    if (gethostname(hostname,sizeof(hostname)) < 0)
	strcpy(hostname,"unknown_host");
    if ((fp=popen(FTP_CMD,"w")) == NULL) {
	alert0("Popen failed for ftp process");
	return;
    }
    status2("Retrieving \"%.100s\" from %.100s",file,host);
    fprintf(fp,"open %s\n",host);
    fprintf(fp,"user anonymous %s@%s\n",username,hostname);
    if (*(appResources.ftpType))
	fprintf(fp,"type %s\n",appResources.ftpType);
    if (*(appResources.ftpDir))
	fprintf(fp,"lcd %s\n",appResources.ftpDir);
    fprintf(fp,"cd %s\n",loc);
    fprintf(fp,"get %s\n",file);
    status = pclose(fp) >> 8;
    if (status)
	alert1("Ftp returned error code %d",status);
    status0("Ready");
}
