#!/bin/sh

# Usage:
# Define a lock in restricted time <lifetime>.
# Wait for lock in restricted time [wait_time].

# Lock Command:
# /usr/sbin/draylock <lifetime> <filename> [wait_time] [wait_period] || Fail_handling
# NOTICE: this command exit 1 if system CANNOT get lock.

# Unlock Command:
# /usr/sbin/draylock -u <filename>

# Parameters:
# <lifetime>	: seconds. System will auto unlock if lifetime expires.
# <filename>	: lock file.
# [wait_time]	: seconds, default 60s. MAX time to wait for this lock (exit 1 if system CANNOT get lock).
# [wait_period]	: seconds. default 10s. time to recheck lock.
#				  ex. wait_time=60, wait_period=10 => check lock every 10 sec, at most wait 60 sec then give up.

# Examples:
# /usr/sbin/draylock 900 /tmp/test.lock 60 10 || exit 0
#		If system get lock /tmp/test.lock, this lock is effective for 900 sec (15 min).
#		If system CANNOT get lock, at most wait 60 sec and retry every 10 sec, then give up and exit.
# /usr/sbin/draylock -u /tmp/test.lock
#		Unlock(remove) lock /tmp/test.lock

[ "$2" ] || exit 1
LOCKFILE=$2

if [ "x$1" == "x-u" ]; then
	rm -f $LOCKFILE
else
	LIFETIME=$1
	W_TIME=${3:-60}
	W_PERIOD=${4:-10}
	now=`cat /proc/uptime |cut -d. -f1`

	wait=0
	while [ -e $LOCKFILE ]; do
		locktime=`cat $LOCKFILE`
		[ $now -ge $locktime ] && break
		[ $wait -ge $W_TIME ] && exit 1
		wait=$(($wait + $W_PERIOD))
		sleep $W_PERIOD
		now=`cat /proc/uptime |cut -d. -f1`
	done

	limit=$(($now + $LIFETIME))
	echo "$limit" > $LOCKFILE
fi
exit 0