#!/bin/bash
#
# Copyright (c) International Business Machines  Corp., 2005
# Author: Ram Pai (linuxram@us.ibm.com)
#
# This library is free software; you can redistribute it and/or
# modify it under the terms of the GNU Lesser General Public
# License as published by the Free Software Foundation; either
# version 2.1 of the License, or (at your option) any later version.
#
# This library 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
# Lesser General Public License for more details.
#
# You should have received a copy of the GNU Lesser General Public
# License along with this library; if not, write to the Free Software
# Foundation, Inc., 59 Temple Place, Suite 330, Boston, MA  02111-1307  USA
#


lockfile="/.nslock"
SUCCESS=0
FAIL=1
otherpid=
startparent()
{
	rm -f $lockfile
	echo $$ >| ${lockfile}parent
	while [ 1 ]
	do
		otherpid="$(cat ${lockfile}child 2> /dev/null)"
		if [ -n "$otherpid" -a -d /proc/$otherpid ]
		then
			return
		fi
	done
}

startchild()
{
	rm -f $lockfile
	echo $$ >| ${lockfile}child
	while [ 1 ]
	do
		otherpid="$(cat ${lockfile}parent 2> /dev/null)"
		if [ -n "$otherpid" -a -d /proc/$otherpid ]
		then
			return
		fi
	done
}

iamgoingahead()
{
	while [ 1 ]
	do
		if [ ! -d /proc/$otherpid ]
		then
			return $FAIL
		fi
		str=`cat $lockfile 2> /dev/null`
		pid=$(echo $str | awk '{print $1}')
		error=$(echo $str | awk '{print $2}')
		if [ "$pid" == "$$" ]
		then
			return $error
		fi
		sleep 1
	done
}


goahead()
{
	set -x
	ret=$SUCCESS
	if [ -n "$1" ]
	then
		ret=$1
	fi
	echo "$otherpid $ret" >| $lockfile
	set +x
}