/*
 *	Copyright 1988 by Rayan S. Zachariassen, all rights reserved.
 *	This will be free software, but only when it is finished.
 */

/*
 * Common routine to fiddle control file tag characters.
 */

#include <stdio.h>
#include "hostenv.h"
#include <sys/file.h>
#include "mail.h"

#ifndef	L_SET
#define	L_SET	0
#endif	/* L_SET */

int
lockaddr(fd, offset, was, new)
	int	fd;
	long	offset;
	char	was;
	char	new;
{
	char	lockbuf[1+_CFTAG_RCPTPIDSIZE+1];
	int	newlock = 0;

	if (lseek(fd, offset, L_SET) < 0L) {
		(void) fprintf(stderr, "lockaddr: lseek failure\n");
		return 0;
	}
	if (read(fd, lockbuf, sizeof(lockbuf)) != sizeof(lockbuf)) {
		(void) fprintf(stderr, "lockaddr: read failure\n");
		return 0;
	}
	newlock = ((lockbuf[1] == ' ') ||
		   (lockbuf[1] >= '0' && lockbuf[1] <= '9'));
	if (lockbuf[0] == was) {
		if (lseek(fd, offset, L_SET) < 0L) {
			fprintf(stderr, "lockaddr: lseek2 failure\n");
			return 0;
		}
		if (write(fd, &new, 1) != 1) return 0;
		if (newlock) {
		  if (new == _CFTAG_LOCK) {
		    /* Mark the lock with client process-id */
		    sprintf(lockbuf+1,"%*d",_CFTAG_RCPTPIDSIZE,getpid());
		    if (write(fd,lockbuf+1,_CFTAG_RCPTPIDSIZE) != _CFTAG_RCPTPIDSIZE)
		      return 0;
		  } else {
		    /* Clear the lock location */
		    sprintf(lockbuf+1,"%*s",_CFTAG_RCPTPIDSIZE,"");
		    if (write(fd,lockbuf+1,_CFTAG_RCPTPIDSIZE) != _CFTAG_RCPTPIDSIZE)
		      return 0;
		  }
		}
		return 1;
	}
	fprintf(stderr, "lockaddr: expected '%c' found '%c'\n", was, new);
	return 0;
}

