/* delete.c - remove an entry from the current file
 */

#include <ctype.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include <unistd.h>
#include "terminal.h"
#include "viewfile.h"
#include "hook.h"


/* Delete an entry from the current file.
 */
void rf_delete_entry(rf_data_t data)
{
	struct stat sb;
	int r, fd;
	long pos;
	long e, l, t;
	size_t a, b;
	char *p;

	if (data->flags & MENU_STATUS_READONLY)
		return;
	if (data->flags & MENU_STATUS_BARDELETE)
		return;
	if ((!(data->flags & MENU_STATUS_ADD))
	    && !(data->flags & MENU_STATUS_DELETE))
		return;

	if (bbs_hook(HOOK_CHECK_BAN, "E", 0)) {
		t_goto(0, t_rows - 1);
		t_clrtoeol();
		t_centre
		    ("\035R  *** You are banned from altering files ***  \035r");
		sleep(2);
		rf_redraw = 1;
		return;
	}

	pos = data->ldb_entry->current_line;

	r = rf_scan_entries(data, &pos,
			    "[\035BY\035b]:Delete  [\035BQ\035b]:Quit",
			    "Y",
			    (data->flags & MENU_STATUS_DELETE) ? 0 : 1,
			    (data->
			     flags & MENU_STATUS_DELETE) ? 0 :
			    current_user);

	if (r == 'Q')
		return;

	if (!(data->flags & MENU_STATUS_BARLOG))
		bbs_hook(HOOK_LOG_DELETE, data, &pos);

	if (rf_edit_lock(data->ldb_entry->realname))
		return;			    /* lock file */

	fd = open(data->ldb_entry->realname, O_RDWR);
	if (fd < 0) {
		rf_edit_unlock();
		return;
	}

	for (e = pos + 1; (e < data->num_lines)
	     && (data->line_pos[e].type != MFILE_LINE_DATESTAMP); e++);	/* find end of entry */

	if (e < data->num_lines) {
		fstat(fd, &sb);
		e = data->line_pos[e].offset - data->line_pos[pos].offset;
		l = sb.st_size - e;
		pos = data->line_pos[pos].offset + e;
		while (pos < sb.st_size) {  /* move file contents */
			t = sb.st_size - pos;
			if (t < 0)
				t = 0;
			if (t > sizeof(data->linebuf))
				t = sizeof(data->linebuf);
			lseek(fd, pos, SEEK_SET);
			a = read(fd, data->linebuf, t);
			if (a < 0)
				continue;
			t = a;
			lseek(fd, pos - e, SEEK_SET);
			p = data->linebuf;
			while (a > 0) {
				b = write(fd, p, a);
				if (b < 0)
					continue;
				a -= b;
				p += b;
			}
			pos += t;
		}
	} else {
		l = data->line_pos[pos].offset;
	}

	ftruncate(fd, l);		    /* truncate file */
	close(fd);

	rf_edit_unlock();		    /* unlock */
}

/* EOF */
