#!/bin/bash

# Settings variables go here
timeout="0"
progname="Programm"
message=""
conflict_code="111"
remote_flock=""

show_help() {
cat <<EOF
Usage: foxde-once [<option> ...] <lockfile> <command> [<arg> ...]

OPTIONS:
-n|--name <name>
	The program name to use for the error message.
-w, --wait, --timeout <seconds>
	How long to wait until the error message is shown
	Default: 0
-E, --conflict-exit-code <code>
	Which exit code to use to communicate an access conflict
	Default: 111
-m|--message <message>
	The message used to communicate that there already is someone else using the program.
--remote-flock
	Run the given command directly whithout the flock wrapping, useful for remote checking via ssh.
	Ignores most arguments including the lockfile, which is still required.
EOF
}

set -e
while [[ "$#" -gt 0 ]]; do
	case "$1" in
		-n|--name) progname="$2"; shift 2;;
		-w|--wait|--timeout) timeout="$2"; shift 2;;
		-E|--conflict-exit-code) conflict_code="$2"; shift 2;;
		-m|--message) message="$2"; shift 2;;
		--remote-flock) remote_flock="y"; shift 1;;

		--) break ;;
		--help) show_help; exit 0;;
		-*) printf "Unknown option: %s\n" "$1"; exit 1;;
		*) break
	esac
done
set +e

lockfile="$1"
if ! shift 1 ; then
	show_help
	exit 1
fi

if [ -z "$lockfile" ] || [ $#"" -eq 0 ] ; then
	show_help
	exit 1
fi


# Logic goes here

if [ -z "$remote_flock" ] ; then
	touch "$lockfile"
	flock -w "$timeout" -E "$conflict_code" "$lockfile" "$@"
	code="$?"
else
	"$@"
	code="$?"
fi
if [ "$code" -eq "$conflict_code" ] ; then
	[ -n "$message" ] || message="$progname wird bereits verwendet."
	kdialog --error "$message" --title "$progname"
fi

exit "$code"
