#! /bin/sh
# wrapper to prevent running multiple instances of tin
# 2000-01-19 <urs@tin.org>

prog=/usr/local/bin/tin

name=`basename "$prog"`
host=`hostname`
pid=$$
lock="$host	$pid"

if test -d "${TIN_HOMEDIR-"$HOME"}" ; then
	lockdir="${TIN_HOMEDIR-"$HOME"}/.tin"
	file=tinlock
else
	lockdir="${TMPDIR-/tmp}"
	if test -z "$USER"; then
		if test -z "$UID" ; then
			UID=`id|sed 's,uid=\([0-9]\+\).*,\1,'`
		fi
	fi
	file="tinlock.${USER-"$UID"}"
fi

lockfile="${lockdir}/${file}"
locklink="${lockfile}.lnk"

lcknrun() {
	trap 'rm -f "$locklink" "$lockfile"; exit' 0 1 2 3 15
	(echo "$lock" > "$lockfile" && "$prog" ${1+"$@"} && rm -f "$lockfile" "$locklink") || echo "Oops!"
	exit 0
}

ln -s "$lockfile" "$locklink" 2>/dev/null && lcknrun ${1+"$@"}

##

echo "Found \"$locklink\"!"
if test -f "$lockfile" ; then
	echo "Another $name likely running on:"
    awk '{print $1" with pid: "$2"?"}' < "$lockfile"
else
    echo ", but lock information file \"$lockfile\" missing"
fi
echo "(q)uit - start (r)ead-only - (d)elete lock and start normal."
IFS= read -r key

case $key in
	[dD]*)
		echo "Removing \"$locklink\"  and starting $name normal..."
		rm -f "$locklink" || (echo "Can't delete \"$locklink\"" ; exit 1)
		ln -s "$lockfile" "$locklink" 2>/dev/null && lcknrun
		;;
	[rR]*)
		echo "Starting $name in no-write (-X) mode..."
		"$prog" -X ${1+"$@"}
		echo "There might still be copy(s) of $name running"
		if test -f "$lockfile" ; then
			awk '{print "on: "$1" with pid: "$2}' < "$lockfile"
		fi
		echo "If this is not the case remember to remove \"$locklink\""
		echo "(and \"$lockfile\")."
		;;
	*)
		echo "Aborting..."
		exit 1
		;;
esac
