#include "fido.h"
#include "fidomem.h"
#include <xfbuf.h>
#include "proto.h"

/* Files subsystem. If dumb caller, display help. Get commands, execute .*/

void file_menu() {
char *ap,*cp,path[SS];
int i,n;

/* Check the file area the caller defaults to; if its not valid
anymore, force them to area 1; if thats not valid, kick them out. */

	n= 0;				/* assume no good */
	if (getfarea(caller.files)) 
		if (allowed(&filearea)) n= 1;

	if (! n) {			/* if no valid area, */
		for (i= 0; getfarea(i); i++) {
			if (allowed(&filearea)) {
				n= 1;
				break;
			}
		}
	}
	if (! n) {
		mprintf(CM+20);			/* no valid file areas */
		lprintf(LM+14);			/* log it */
		return;
	}
	while (1) {
		caller.files= filearea.number;			/* remember last file area */
		if (! isargs()) {
			mcrlf();				/* separates commands */
			if (*ovpath) mprintf(CM+21,ovpath);	/* override path */
			else dsparea(CM+256,&filearea,':');	/* or the file area */
		}
		switch(prompt(fido.cmd.file,CM+22,"file.hlp",0)) {
			case 2: if (isargs()) ap= getarg(FM+0); else ap= "";
				file_disp(ap); break;
			case 3: download(); break;
			case 4: upload(); break;
			case 5: chdir(); break;
			case 6: ftype(); break;

			case 7: stats(1); break;
			case 8: ffind(); break;
			case 9: dir(); break;
			case 10: fdelete(); break;
			case 11: setovpath(); break;
			case 12: goodbye(""); break;
			case 13: return;
		}
	}
}

/* List disk files. */

static dir() {
struct _xfbuf xfbuf;
long size;
int i,x;
char *cp,name[SS],spec[SS];

#define SY 0x04		/* System attribute, */
#define HI 0x02		/* Hidden attribute, */
#define RO 0x01		/* Read only attribute. */
#define AR 0x20		/* Archive, */
#define VO 0x08		/* Volume ID */
#define DI 0x10		/* directory */

	cp= getarg(CM+261);
	if (*cp) cpyarg(name,cp);
	else strcpy(name,"*.*");
	makefname(spec,name);

	size= 0L; 
	xfbuf.s_attrib= 0xff; i= 0;
	while (_find(spec,i,&xfbuf) && !abort) {
		++i;
		if (xfbuf.f_attrib & DI) {		/* directory */
			if (uval(CLR_PRV,CLR_PRVS) < SYSOP) continue;
			stoupper(xfbuf.name);
			mprintf(0,"%12s %8s ",xfbuf.name,"<dir>");

		} else {				/* file */
			stolower(xfbuf.name);
			mprintf(0,"%12s %8lu ",xfbuf.name,xfbuf.fsize);
			size += xfbuf.fsize;
		}
		dos_date(&xfbuf);
		dos_time(&xfbuf);
		mprintf(0,"%c%c%c%c ",			/* attributes */
		    ((xfbuf.f_attrib & AR) ? 'A' : '.'),
		    ((xfbuf.f_attrib & SY) ? 'S' : '.'),
		    ((xfbuf.f_attrib & RO) ? 'R' : '.'),
		    ((xfbuf.f_attrib & HI) ? 'H' : '.'));

		mcrlf();
	}
	xfer_time(spec,&i,&i);
}
/* Display the date from within an xfbuf. "99 Jan 84, 12:00p" */

char _months[13][4] = {
	"Eh?",
	"Jan",
	"Feb",
	"Mar",
	"Apr",
	"May",
	"Jun",
	"Jul",
	"Aug",
	"Sep",
	"Oct",
	"Nov",
	"Dec"
};

void dos_date(b)
struct _xfbuf *b;
{

	mprintf(0,"%02u %s %02u ",b-> date & 0x1f,
	    _months[(b-> date >> 5) & 0x0f],
	    ((b-> date >> 9) & 0x3f) + 80);
}

void dos_time(b)
struct _xfbuf *b;
{
	mprintf(0,"%02u:%02u ",b-> time >> 11,(b-> time >> 5) & 0x3f);
}
