# IBM(c) 2007 EPL license http://www.eclipse.org/legal/epl-v10.html
export LOCKDIR=/var/lock/xcat


function needhelp
{
    if [ "$#" = "1" ]
    then
        for i in $*
        do
            test "$i" = "--help" && echo "\nhttp://xcat.org for support." && return 0
            test "$i" = "-h" && echo "http://xcat.org for support.\n" && return 0
            test "$i" = "--version" && echo "$VERSION" && exit 0
            test "$i" = "-v" && echo "$VERSION" && exit 0
        done
    fi
    return 1
}




function getlock
{
    LOCK=$1
    TIMEOUT=$2
    let t=0

    mkdir -p $LOCKDIR

    if [ -r $LOCKDIR/$LOCK.pid ]
    then
        PID=$(cat $LOCKDIR/$LOCK.pid)
        while ps -p $PID >/dev/null 2>&1
        do
            sleep 1
            let t=t+1
            if (($t -gt $TIMEOUT))
            then
                return 1
            fi
        done
    fi

    echo "$$" > $LOCKDIR/$LOCK.pid
    return 0
}

function lockstatus
{
    LOCK=$1

    if [ -r $LOCKDIR/$LOCK.pid ]
    then
        PID=$(cat $LOCKDIR/$LOCK.pid)
        if ps -p $PID >/dev/null 2>&1
        then
            echo "locked by PID $PID"
            ps -fp $PID | tail -1
        else
            echo "stale lock PID $PID, remove $LOCKDIR/$LOCK.pid"
        fi

        return 0
    fi

    echo "nolock"
    return 0
}

function freelock
{
    LOCK=$1
    FORCE=$2

    mkdir -p $LOCKDIR

    if [ "$FORCE" = "1" ]
    then
        rm -f $LOCKDIR/$LOCK.pid >/dev/null 2>&1
        return 0
    fi

    if [ -r $LOCKDIR/$LOCK.pid ]
    then
        PID=$(cat $LOCKDIR/$LOCK.pid)
        if [ "$PID" = "$$" ]
        then
            rm -f $LOCKDIR/$LOCK.pid
        else
            return 1
        fi
    fi

    return 0
}

