#!/bin/sh -e
#
#    run-one - run just one instance at a time of some command and
#              unique set of arguments (useful for cronjobs, eg)
#
#    run-this-one - kill any identical command/args processes
#                   before running this one
#
#    Copyright (C) 2010 Dustin Kirkland <kirkland@ubuntu.com>
#
#    Authors:
#        Dustin Kirkland <kirkland@ubuntu.com>
#
#    This program is free software: you can redistribute it and/or modify
#    it under the terms of the GNU General Public License as published by
#    the Free Software Foundation, either version 3 of the License.
#
#    This program is distributed in the hope that it will be useful,
#    but WITHOUT ANY WARRANTY; without even the implied warranty of
#    MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
#    GNU General Public License for more details.
#
#    You should have received a copy of the GNU General Public License
#    along with this program.  If not, see <http://www.gnu.org/licenses/>.

PROG="run-one"

# Cache hashes here, to keep one user from DoS'ing another
DIR="$HOME/.cache/$PROG"
mkdir -p "$DIR"

# Calculate the hash of the command and arguments
CMDHASH=$(echo "$@" | md5sum | awk '{print $1}')
FLAG="$DIR/$CMDHASH"

# Handle run-this-one invocation, by killing matching process first
case "$(basename $0)" in
	run-this-one)
		ps="$@"
		# Loop through matching pids
		for p in $(pgrep -u "$USER" -f "^$ps$" || true); do
			# Try to kill pid
			kill $p
			# And then block until killed
			while ps $p >/dev/null 2>&1; do
				kill $p
				sleep 1
			done
		done
		# NOTE: Would love to use lsof, but it seems that flock()'s
		# are not persistent enough, sometimes; use pgrep/pkill now.
		# pid=$(lsof "$FLAG" | grep "^flock" | awk '{print $2}') || true
		# [ -z "$pid" ] || kill $pid

	;;
esac

# Run the specified commands, assuming we can flock this command string's hash
flock -xn "$FLAG" "$@"
