/* forward.c - function for sending message from a file
 */

#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include "viewfile.h"
#include "terminal.h"
#include "hook.h"
#include "u2u.h"

extern int hook_check_ban(char *);


/* Deal with an [S] keypress in a file.
 */
void u2u_file_send(rf_data_t data)
{
	long line_start, line_end;
	char keypath[64];
	FILE *fptr;
	char *recipients;
	char *a;
	char *b;
	int c;

	keypath[0] = 0;
	bbs_hook(HOOK_GET_KEYPATH, &a, 0);
	if (a)
		strncpy(keypath, a, sizeof(keypath) - 1);

	if (hook_check_ban("2")) {	    /* banned from sending messages */
		t_goto(0, t_rows - 1);
		t_clrtoeol();
		t_centre
		    ("\035R  *** You are banned from sending messages ***  \035r");
		sleep(2);
		rf_wipe_footer(data);
		rf_footer(data);
		return;
	}

	line_start = data->ldb_entry->current_line;

	c = rf_scan_entries(data, &line_start, "[\035BSPACE\035b]:Send  "
			    "[\035BI\035b]:Inc  "
			    "[\035BF\035b]:Fwd  "
			    "[\035BQ\035b]", " IF", 0, "");

	if ((c == 'Q') || (line_start < 0)) {
		rf_wipe_footer(data);
		rf_footer(data);
		return;
	}

	line_start++;
	for (line_end = line_start; (line_end < data->num_lines)
	     && (data->line_pos[line_end].type != MFILE_LINE_DATESTAMP);
	     line_end++);

	rf_read_line(data, line_start);
	a = strrchr(data->linebuf, '(');
	if (!a)
		return;

	*a = 0;
	a++;
	b = strchr(a, ':');
	if (b)
		*b = 0;
	b = strchr(a, ')');
	if (b)
		*b = 0;

	if (c == 'F') {			    /* ask the user who to send to */
		recipients = u2u_get_recipients();
		if (!recipients) {
			rf_redraw = 1;
			return;
		}
	} else
		recipients = strdup(a);

	if (c == ' ') {
		u2u_send_to(recipients);
		free(recipients);
		bbs_hook(HOOK_SET_ACTION, "Reading ",
			 (data->
			  flags & MENU_STATUS_HIDETITLE) ? "" : data->
			 title);
		rf_redraw = 1;
		return;
	}

	b = u2u_create_file(recipients);
	fptr = fopen(b, "w");
	if (!fptr) {
		u2u_remove_file(recipients);
		free(recipients);
		return;
	}

	fprintf(fptr, "\n\n");

	if (c == 'F') {
		fprintf(fptr, "\035S--- Forwarded Message ---\035s\n");
		fprintf(fptr, "Orig-From: %s\n", a);
		fprintf(fptr, "Source: %s\n\n", data->title);
	}

	line_start += 2;
	for (; (line_start < line_end)
	     && (data->line_pos[line_start].type == MFILE_LINE_BLANK);
	     line_start++);

	for (; line_start < line_end; line_start++) {
		rf_read_line(data, line_start);
		fprintf(fptr, "%s%s\n", (c == 'I') ? "> " : "",
			data->linebuf);
	}

	fclose(fptr);

	u2u_send_to(recipients);
	free(recipients);

	bbs_hook(HOOK_SET_ACTION, "Reading ",
		 (data->flags & MENU_STATUS_HIDETITLE) ? "" : data->title);
	bbs_hook(HOOK_SET_KEYPATH, keypath, 0);
	rf_redraw = 1;
}

/* EOF */
