#!/bin/bash

#------------------------------------------------------------------------
# September, 2014, Balaji Krishnamoorthy
# Copyright (c) 2014-2017, 2019 by Cisco Systems, Inc.
# All Rights Reserved
#------------------------------------------------------------------------

function usagexit() {
    echo ""
    echo "  USAGE : $0 R/S VM"
    echo "          R : Rack range LCC:0 to 15, FCC:F0 to F3"
    echo "          S : RP0|RP1|SC0|SC1|[0-15]"
    echo ""
    echo "    VM is sysadmin|XR-RP|XR-LC"
    exit 1
} >&2

[[ $# -lt 2 ]] && { echo "Incorrect number of arguments!!" >&2; usagexit; }

MYADDR=$(ifconfig eth-vf1.3073 | grep 'inet addr:' | awk '{print $2}' | awk -F: '{print $2}')

CONFDADDR=$(ds_test_client -l confd6 | tail -1 | awk -F, '{print $2}' | awk -F= '{print $2}')

location=$(echo $1 | tr [:lower:] [:upper:])
location_=$( echo $location | tr '/' '_')
vm=$2

thisRS=$(hostname | cut -d':' -f2 | tr '_' '/')
thisRS_=$(hostname | cut -d':' -f2)

if [[ "$MYADDR" != "$CONFDADDR" ]]; then
    scp -p ${CONFDADDR}:/tmp/show.node.inventory_${thisRS_} /tmp >& /dev/null
fi
find /tmp -maxdepth 1 -cmin -10 | grep 'show\.node\.inventory_${thisRS}' >& /dev/null
if [[ $? -ne 0 ]]; then
    show_cmd "show node-inventory detail location $thisRS | save /tmp/show.node.inventory_${thisRS}" >& /dev/null
    if [[ "$MYADDR" != "$CONFDADDR" ]]; then
        scp -p ${CONFDADDR}:/tmp/show.node.inventory_${thisRS_} /tmp >& /dev/null
    fi
fi

if [[ "$MYADDR" != "$CONFDADDR" ]]; then
    scp -p ${CONFDADDR}:/tmp/inventory1_${location_} /tmp >& /dev/null
fi
find /tmp -maxdepth 1 -cmin -10 | grep 'inventory1_${location}' >& /dev/null
if [[ $? -ne 0 ]]; then
    show_cmd "show inventory location $location | save /tmp/inventory1_${location}" >& /dev/null
    if [[ "$MYADDR" != "$CONFDADDR" ]]; then
         scp -p ${CONFDADDR}:/tmp/inventory1_${location_} /tmp >& /dev/null
    fi
fi

if [ ! -e /tmp/inventory1_${location_} ]; then
    exit 1
fi

card_sn=$(grep 'SN:' /tmp/inventory1_${location} | awk '{print $NF}')

if [ $card_sn != "" ]; then
    grep "${card_sn}" /tmp/show.node.inventory_${thisRS} |  grep "${vm}" | cut -b10-22 | sed -e 's/  *//g'
fi

