#include <unistd.h>
#include <fcntl.h>
#include <stdlib.h>
#include <string.h>
#include <sys/types.h>
#include <sys/stat.h>
#include <sys/file.h>
#include "iolib.h"
#include "freedt.h"
#include "config.h"
const char *progname = "setlock";
const char *proghelp =
	"Usage: setlock [OPTIONS] lockfile command ...\n"
	"Run a command with an advisory lock set on a file.\n\n"
	"-n        If the lock is already held, exit immediately\n"
	"-N        If the lock is already held, block (default)\n"
	"-x        On error, exit silently with rc 0\n"
	"-X        On error, exit noisily with rc 111 (default)\n";

int error = 1;

void fail(const char *msg1, const char *msg2) {
	if (error)
		die2(msg1, msg2);
	else
		exit(0);
}

int main(int argc, char **argv) {
	int fd, block = 1;

	while (1) {
		int c = getopt(argc, argv, "+V?nNxX");
		if (c == -1)
			break;
		switch (c) {
		case 'n':
			block = 0;
			break;
		case 'N':
			block = 1;
			break;
		case 'x':
			error = 0;
			break;
		case 'X':
			error = 1;
			break;
		case 'V':
			version();
		default:
			help();
		}
	}

	if ((argc - optind) < 2)
		help();

	fd = open(argv[optind], O_WRONLY | O_CREAT, 0600);
	if (fd < 0)
		fail(argv[optind], "unable to open");
	if (fcntl(fd, F_SETFD, 0) < 0)
		fail(argv[optind], "unable to set fd non-close-on-exec");
	if (lock_fd(fd, block) < 0)
		fail(argv[optind], "unable to lock");

	execvp(argv[optind + 1], &argv[optind + 1]);
	die2(argv[optind + 1], "unable to exec");

	return 0; /* NOTREACHED */
}



syntax highlighted by Code2HTML, v. 0.9.1