#****************************************************************************
#  ##   ##         #####   #####  ##     **        NoSQL RDBMS - lock       *
#  ###  ##        ####### ####### ##     **      $Revision: 2.1 $			*
#  #### ##        ###     ##   ## ##     ************************************
#  #######  ####  #####   ##   ## ##     **      Carlo Strozzi (c) 1998     *
#  ####### ######   ##### ## # ## ##     ************************************
#  ## #### ##  ##     ### ##  ### ##     **           Written by            *
#  ##  ### ###### ####### ######  ###### **          Carlo Strozzi          *
#  ##   ##  ####   #####   #### # ###### **     e-mail: carlos@linux.it     *
#****************************************************************************
#   NoSQL RDBMS, Copyright (C) 1998 Carlo Strozzi.                          *
#   This program comes with ABSOLUTELY NO WARRANTY; for details             *
#   refer to the GNU General Public License.                                *
#****************************************************************************
#
# Built-in table locking program for NoSQL.
#
# Usage:  nosql lock table [ table ... ]
#
# NoSQL built-in file locking utility.
#
##########################################################################

Exit ()
{
  rm -f "${traplist}"
  exit $1
}

# Set the name of the lockfile creation program.                             
locker=${NSQLIB}/bin/shlock

while [ $# -gt 0 ]
do
  # Emulate the default timeout interval of lockfile(1).
  # I do not use seq(1) here, as some systems may not have it.
  for lock_i in 1 2 3 4 5 6 7 8 9
  do
		if test ${lock_i} -eq 9
		then
		  echo "nosql lock: timed out on ${lock_file}" >&2 
		  Exit 1
		fi

		# Provide the .LCK extension if not already present.
		# This is necessary to require only the table name as
		# argument, regardless of whether we are using this
		# locking program or whatever else specified by NSQLOCKER.
		lock_file=$1
		test "$(basename $1 .LCK)" = $1 && lock_file=${lock_file}.LCK

	    if ${locker} -f ${lock_file} -p $$ -a
	    then
		    traplist="${traplist} ${lock_file}"
		    trap "rm -f ${traplist}" 1 2 15
		    shift
		    break
	    else
			echo "nosql lock: trying to set ${lock_file} ... " >&2
		    sleep 1
	    fi
  done
done

