/*
 * This code is part of Screws project.
 * Copylefted by pancake@phreaker.net at 2003
 */

/* File mutex implementation using sticky bit by pancake */
#include "Fmutex.h"

bool use_fmutex=true;

int
fmutex_init(file)
	const char *file;
{
	struct stat st;
	if (Svr.nolock) return true;

	if (file[0]=='|') return true;

   chmod (file,S_IRWXU);
	if ( stat(file,&st) <0 )
	{
		if (creat(file,S_IRWXU) <0)
		{
			fprintf(stderr,"Cannot create logfile '%s'. fmutex disabled\n",file);
			use_fmutex=false;
			return false;
		}
		stat(file,&st);
	}
	fmutex_unlock(file,st.st_mode);
	return st.st_mode;
}

int
fmutex_lock(file)
	const char *file;
{
	struct stat st;
	if (Svr.nolock||!use_fmutex) return 0;

	while(1)
	{
		stat(file,&st);
		if (! (st.st_mode&S_ISVTX )) break;
		sleep(Svr.usleep);
	}
	chmod(file,st.st_mode+S_ISVTX);
	return st.st_mode;
}

int
fmutex_unlock(file,mode)
	const char *file;
	int mode;
{
	if (Svr.nolock||!use_fmutex) return 0;
	return chmod(file,mode&(mode+S_ISVTX));
}
