/* readfile.c - cause a file to be read
 */

#ifdef HAVE_CONFIG_H
#include "config.h"
#endif				/* HAVE_CONFIG_H */
#include <stdlib.h>
#include <string.h>
#include <sys/stat.h>
#include <unistd.h>
#include "hook.h"
#include "viewfile.h"
#include "viewmenu.h"


/* Display the file "file" in the file viewer.
 */
void menuview_readfile(menudata_t data, char *file, char *title,
		       unsigned long flags, char *cm)
{
	struct LDB d;
	int r;

	bbs_hook(HOOK_SET_ACTION, "Reading ",
		 (flags & MENU_STATUS_HIDETITLE) ? "" : title);
	bbs_hook(HOOK_SET_KEYPATH, data->buf, 0);

	ldb_read(data->ldbfile, file, &d);
	strcpy(d.realname, file);
	r = do_read_file(&d, title, flags, cm);
	if (flags & MENU_STATUS_NOLAST)
		r = 2;
	if (r != 2)
		ldb_write(data->ldbfile, &d);
}


/* Display the file "file" in the file viewer if it has been changed since
 * last time it was viewed. Returns non-zero if [Q] was pressed to exit the
 * viewfile instead of a read failure, [C], or [RETURN].
 */
int menuview_viewfile(menudata_t data, char *file, char *title)
{
	struct stat sb;
	struct LDB d;
	int r = 0;
	char *a;

	if (stat(file, &sb))
		return (0);

	ldb_read(data->ldbfile, file, &d);
	strcpy(d.realname, file);

	if ((d.last_accessed <= sb.st_mtime) || (d.at_end == 0)) {
		bbs_hook(HOOK_SET_ACTION, "Viewing info on ", title);
		bbs_hook(HOOK_SET_KEYPATH, data->buf, 0);
		a = getenv("BBS_SPACE_EXIT");
		if (!a)
			a = "0";
		a = strdup(a);
		setenv("BBS_SPACE_EXIT", "0", 1);
		r = do_read_file(&d, title, MENU_STATUS_READONLY, 0);
		setenv("BBS_SPACE_EXIT", a, 1);
		free(a);
		if (r != 2)
			ldb_write(data->ldbfile, &d);
	}

	if (r == 1)
		return (1);
	return (0);
}


/* Display the file "file" in the file viewer, then return non-zero if [Q]
 * was pressed to exit the viewfile instead of a read failure, [C], or
 * [RETURN].
 */
int menuview_viewalways(menudata_t data, char *file, char *title)
{
	struct LDB d;
	char *a;
	int r;

	bbs_hook(HOOK_SET_ACTION, "Viewing info on ", title);
	bbs_hook(HOOK_SET_KEYPATH, data->buf, 0);

	ldb_read(data->ldbfile, file, &d);
	strcpy(d.realname, file);
	a = getenv("BBS_SPACE_EXIT");
	if (!a)
		a = "0";
	a = strdup(a);
	setenv("BBS_SPACE_EXIT", "0", 1);
	r = do_read_file(&d, title, MENU_STATUS_READONLY, 0);
	setenv("BBS_SPACE_EXIT", a, 1);
	free(a);
	if (r != 2)
		ldb_write(data->ldbfile, &d);

	if (r == 1)
		return (1);
	return (0);
}

/* EOF */
