/*
 * Copyright 2001, 2002, 2003 Adam Sampson <ats@offog.org>
 *
 * Permission to use, copy, modify, and/or distribute this software for any
 * purpose with or without fee is hereby granted, provided that the above
 * copyright notice and this permission notice appear in all copies.
 *
 * THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES
 * WITH REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF
 * MERCHANTABILITY AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR
 * ANY SPECIAL, DIRECT, INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES
 * WHATSOEVER RESULTING FROM LOSS OF USE, DATA OR PROFITS, WHETHER IN AN
 * ACTION OF CONTRACT, NEGLIGENCE OR OTHER TORTIOUS ACTION, ARISING OUT OF
 * OR IN CONNECTION WITH THE USE OR PERFORMANCE OF THIS SOFTWARE.
 */

#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 */
}

