#!/bin/bash
################################################################################
# Filename: ./src/base/hooks/qrm-node-ext-id
# 
# The contents of this file are subject to the Qlusters Public License
# Version 1.1 (the License); you may not use this file except in compliance
# with the License.
# You may obtain a copy of the License at
# http://www.openqrm.org/content/view/33/69/.
# 
# Software distributed under the License is distributed on an AS IS basis,
# WITHOUT WARRANTY OF ANY KIND, either express or implied. See the License for
# the specific language governing rights and limitations under the License.
# 
# The Original Code is openQRM.
# 
# The Initial Developer of the Original Code is Qlusters Corporation. Portions
# created by Qlusters Corporation are Copyright (C) 2003-2005. All Rights
# Reserved.
# 
# Contributor(s):
# 
# Description:
# 
# Comments:
################################################################################
###########################################################
###   This script searches /root/qrm-nodes.conf          ###
###   in order to get node id by specified MAC address  ###
###########################################################

MAC=$NODE_MAC
IP=$NODE_IP

CUR_DIR=`dirname $0`
QRM_DATA_DIR=$CUR_DIR/..

if [  -z $MAC ]; then
        echo "ERROR: MAC address wasn't specified" >&2
        exit 1
fi

# lock
DEFAULTLOCK="/var/lock/subsys/`basename $0`"
LOCK=${LOCK:-"$DEFAULTLOCK"}
trap "" 2
if ! lockfile -l 10 $LOCK; then
        echo "Could not create lock $LOCK" >&2
        exit 2
fi
trap "/bin/rm -f $LOCK;exit 3" 2

QRM_NODES="/root/qrm-nodes.conf"

# create nodes file if not exists
if [ ! -e $QRM_NODES ]; then
        touch $QRM_NODES
fi

EXT_ID=`grep $MAC $QRM_NODES | cut -d' ' -f1`
if [ -z $EXT_ID ]; then
        # a new node
        #EXT_ID=`wc -l $QRM_NODES | tr -s ' ' | cut -d' ' -f2`
        EXT_ID=`cat $QRM_NODES | wc -l`
        # take 'safe' offset
        EXT_ID=$(( EXT_ID + 10 ))
        # update nodes file
        echo "$EXT_ID $MAC " >> $QRM_NODES
fi

# unlock
rm -f $LOCK
echo $EXT_ID
