#!/bin/bash
#
# slotr : Used for Reload Remote cards from RP Host
#
# Dec 2014, Jisu 
#
# Copyright (c) 2015, 2020 by Cisco Systems, Inc.
# All rights reserved.
#
if [ -z "$1" ]
  then
    echo "Usage: slotr <slot number>"
    exit
fi

IOFPGA_ID=$(lspci -nd 1137:0100 | tail -1 | awk '{ print $1 }');

if test -z $IOFPGA_ID; then
    echo "Could not determine IOFPGA pci address with lspci"
    exit 1
fi

IO_BASE=0x$(lspci -vs $IOFPGA_ID | egrep -w 'Memo|size=256M' |  awk '{ print $3 }');

IOFPGA_BASE=$(printf 0x%08X $(($IO_BASE + 0x08000000)))

# Steps 
# 1. Check master ship of RP by reading 0xe8000330
# 2. If master RP the proceed to write 
# 3. If salve RP exit with Error message 

# Check Master ship 
ADDR=$(printf 0x%08X $(($IOFPGA_BASE + 0x330)))

MASTER_REG=`iorw r $ADDR w | awk '{print $2}'`
if [ $? -ne 0 ]; then
    echo ""
    echo "ERROR: Failed to read RP Mastership register"
    exit 1
fi

ACTIVE_BIT=`echo ${MASTER_REG:0:1}`
if [ $? -ne 0 ]; then
    echo "ERROR: Failed interpreting RP Mastership status"
    exit 1
fi

if [ "$ACTIVE_BIT" == "1" ]; then
    echo "MASTER-RP: Proceeding to Reload  Slot: $1"
else
    echo "SLAVE-RP: Please run Reload utility from Master RP"
    exit 1
fi

# If MASTER RP reload the slot
ADDR=$(printf 0x%08X $(($IOFPGA_BASE + 0xfc)))

iorw w $ADDR `printf "0x80%02x00ec" $1` w
