#!/bin/bash
#                       /usr/local/bin/filelock
# https://crystalfaeries.net/posix/bin/filelock
# celeste:crystalfaery FILELOCK 2019-07-10 15:41:39+00:00
# From:	filelock - A flexible file-locking mechanism:
# https://www.linuxjournal.com/article/9557

retries="8"				# default number of retries
action="lock"				# default action
nullcmd="/bin/true"			# null command for lockfile

while getopts "lur:" opt
do case $opt in
l ) action="lock" ;;
u ) action="unlock" ;;
r ) retries="$OPTARG" ;;
esac; done
shift $(($OPTIND - 1))
if [ $# -eq 0 ] ;
	then cat >&2 << EOF
Usage: $0 [-l|-u] [-r retries] lockfilename
-l requests a    lock (the default),
-u requests an unlock,
-r X specifies a maximum number of retries before it fails (default = $retries).
EOF
	exit 1	# quick help
fi

# Ascertain whether we have lockf or lockfile system apps
if [ -z "$(which lockfile | grep -v '^no ')" ] ;
then
	echo "$0 failed: 'lockfile' utility not found in PATH." >&2
	exit 1
fi

if [ "$action" = "lock" ] ;
then
	if ! lockfile -1 -r $retries "$1"
	then
		echo "$0: Failed: Couldn't create lockfile in time" >&2
		exit 1
	fi
else
	# action = unlock
	if [ ! -f "$1" ] 
	then
		echo "$0: Warning: lockfile $1 doesn't exist to unlock" >&2
		exit 1
	fi
	rm -f "$1"
fi
exit 0 
