#!/bin/bash
######################################################################
#
#   Bash script waits for device to become available
#    - arg1: PV name from pingDevice.db [$(P)$(M):$(DEV):PING]
#
#   IMPORTANT: If this is used as part of the st.cmd call
#              the PV from arg1 must be loaded in different SIOC
#    
######################################################################

# Store PV
PV=$1

# Check if PV exists
bla=`caget -t $PV 2>/dev/null`
STAT=$?

if [ $STAT -ne 0 ]; then
    echo "Waiting for $PV to be available, please ensure that this PV exists and is alive!"
fi

# Wait while PV isn't available
while [ $STAT -ne 0 ]; do
    sleep 2
    bla=`caget -t $PV 2>/dev/null`
    STAT=$?
done

# Check PV severity
devStat=`caget -t -n -w 30 $PV.SEVR`
DEVICE=`caget -t $PV.INP`

echo "Waiting for device $DEVICE:"
count=0

# Loop while PV severity isn't NO_ALARM
while [ $devStat -ne 0 ]; do
    let count+=1
    if [ $count -ge 30  ]; then
        count=0
        echo -ne "\r                                  \r"
    else
        echo -ne "."
    fi
    sleep 3
    devStat=`caget -t -n -w 6 $PV.SEVR`

done

# Exit when device is online
echo -e "\rDevice $DEVICE online!                        \n"
