/* lock.c - lock/unlock a file
 */

#include <stdlib.h>
#include <string.h>
#include <unistd.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <fcntl.h>
#include "lock.h"
#include "terminal.h"
#include "viewfile.h"

int rf_lock_fd = -1;
char *rf__lock_file = 0;


/* Attempt to lock "file"; returns nonzero on failure. This function should
 * not be called twice in a row, or "rf_lock_fd" will be overwritten and file
 * descriptor leakage will occur.
 */
int rf_edit_lock(char *file)
{
	int tries = 0;

	rf_lock_fd = open(file, O_RDWR);
	if (rf_lock_fd < 0)
		return (1);

	free(rf__lock_file);
	rf__lock_file = strdup(file);

	if (my_flock(file, rf_lock_fd, LOCK_EX | LOCK_NB) == 0)
		return (0);

	t_goto(0, t_rows - 1);
	t_centre(" \035R *** Waiting for Lock - Please Wait *** \035r ");
	t_bored(0);

	while (tries < 5) {
		t_bored(1);
		sleep(1);
		if (my_flock(file, rf_lock_fd, LOCK_EX | LOCK_NB) == 0)
			return (0);
		tries++;
	}

	t_goto(0, t_rows - 1);
	t_centre
	    (" \035R *** File is currently locked - try again later *** \035r ");

	close(rf_lock_fd);
	return (1);
}


/* Unlock the last locked file.
 */
void rf_edit_unlock(void)
{
	if (rf_lock_fd < 0)
		return;
	my_flock(rf__lock_file, rf_lock_fd, LOCK_UN);
	close(rf_lock_fd);
	rf_lock_fd = -1;
	free(rf__lock_file);
	rf__lock_file = 0;
}

/* EOF */
