#!/bin/ksh

LOCK_FILE="$1"
PID="$2"

if [ -f ${LOCK_FILE} ]
then
    lock_pid="`head -1 ${LOCK_FILE} 2>/dev/null`"
    if [ 1 -lt "$lock_pid" ]
    then
        if kill -0 "$lock_pid" 2>/dev/null
        then
            #echo "sh_lock: Lock exists "`cat ${LOCK_FILE}` >&2
            exit 1
        else
            if mv ${LOCK_FILE}.$lock_pid ${LOCK_FILE}.$PID 2>/dev/null
            then
                echo "sh_lock: Removed Stale Lock ${LOCK_FILE}"`cat ${LOCK_FILE}.$PID` >&2
		rm ${LOCK_FILE} ${LOCK_FILE}.$PID || (
		    echo "sh_lock: error cleaning up Stale Lock" >&2
		    exit 1
		)
            else
                echo "sh_lock: Oops, Detected a stale lock, but I could not move it ${LOCK_FILE}" >&2
                exit 1
            fi
        fi
    else
	echo "sh_lock: Lockfile without a PID ${LOCK_FILE}" >&2
    fi
fi
rm ${LOCK_FILE}.$PID 2>/dev/null
if echo "$PID\n`date`" > ${LOCK_FILE}.$PID 2>/dev/null &&
    ln -s ${LOCK_FILE}.$PID ${LOCK_FILE} 2>/dev/null
then
    echo "${LOCK_FILE}" "${LOCK_FILE}.$PID"
    exit 0
else
    rm ${LOCK_FILE}.$PID 2>/dev/null
    exit 1
fi
echo "sh_lock: this should never happen" >&2
exit 2
