#!/bin/sh

#set -x 

function printUsage {
    echo "Usage: $0 [opt] [-f file] [-c channel]"
    echo ""
    echo "Options:"
    echo "  -U: unlatch faults for channel (-c option) or channels (-f option) - no TEST"
    echo "  -f <file>: file containing one channel per line (e.g. BLM:UND1:3321)"
    echo "  -c <channel>: test one channel (PED,TEST,LOSS)"
    echo "  -l: check LOSS PVs"
    echo "  -p: check PED PVs"
    echo "  -t: check TEST PVs"
    echo ""
    echo "Examples:"
    echo "   $0 -f LN37.dat"
    echo "   $0 -c BLM:UND1:3321"
    echo "   $0 -u -c BLM:UND1:3321"
    echo "   $0 -U -c BLM:UND1:3321"
    echo "   $0 -U -f LN37.dat"
    echo "   $0 -l -c BLM:UND1:3321"
}

pvValue=0
retries=5

function getPv {
    for i in {1..5}; do
	pvValue=`caget -n -t $1 2> /dev/null`
	if [ "$?" == 0 ]; then
	    return 0
	fi
    done
    echo "ERROR: Failed to get PV ("$1")"
    return 1
}

function putPv {
    pv=$1
    value=$2

    for i in {1..20}; do
	out=`caput -w 10 $pv $value 2> /dev/null`
	if [ "$?" == 0 ]; then
	    return 0
	fi
    done
    echo "ERROR: Failed to put PV ("$1"="$2")"
    return 0
}

function unlatchChannels {
    rootPv=$1
    verbose=$2
    lossOnly=$3
    pedOnly=$4
    testOnly=$5
    allTests=$6

    if [ "$lossOnly" == "True" -o "$allTests" == "True" ]; then
        pv=$rootPv":LOSS_L_UNLH" 
        if [ "$verbose" == "True" ]; then
            echo "Unlatching "$pv
	fi
	putPv $pv "1"

        pv=$rootPv":LOSS_1_L_UNLH" 
        if [ "$verbose" == "True" ]; then
            echo "Unlatching "$pv
	fi
        putPv $pv "1"

        pv=$rootPv":LOSS_10_L_UNLH" 
        if [ "$verbose" == "True" ]; then
            echo "Unlatching "$pv
	fi
        putPv $pv "1"

        pv=$rootPv":LOSS_30_L_UNLH" 
        if [ "$verbose" == "True" ]; then
            echo "Unlatching "$pv
	fi
        putPv $pv "1"

        pv=$rootPv":LOSS_60_L_UNLH" 
        if [ "$verbose" == "True" ]; then
            echo "Unlatching "$pv
	fi
        putPv $pv "1"

        pv=$rootPv":LOSS_H_UNLH" 
        if [ "$verbose" == "True" ]; then
            echo "Unlatching "$pv
	fi
        putPv $pv "1"

        pv=$rootPv":LOSS_1_H_UNLH" 
        if [ "$verbose" == "True" ]; then
            echo "Unlatching "$pv
	fi
        putPv $pv "1"

        pv=$rootPv":LOSS_10_H_UNLH" 
        if [ "$verbose" == "True" ]; then
            echo "Unlatching "$pv
	fi
        putPv $pv "1"

        pv=$rootPv":LOSS_30_H_UNLH" 
        if [ "$verbose" == "True" ]; then
            echo "Unlatching "$pv
	fi
        putPv $pv "1"

        pv=$rootPv":LOSS_60_H_UNLH" 
        if [ "$verbose" == "True" ]; then
            echo "Unlatching "$pv
	fi
        putPv $pv "1"
    fi

    if [ "$testOnly" == "True" -o "$allTests" == "True" ]; then
	testType="TEST"
	# Check if PV exists
	`cainfo $rootPv:TEST_L 2>&1 | grep Native | grep TYPENOTCONN &> /dev/null`
	if [ "$?" == "1" ]; then
	    testType="TEST"
	fi

	`cainfo $rootPv:TIMING_L 2>&1 | grep Native | grep TYPENOTCONN &> /dev/null`
	if [ "$?" == "1" ]; then
	    testType="TIMING"
	fi

	`cainfo $rootPv:HRTBT_L 2>&1 | grep Native | grep TYPENOTCONN &> /dev/null`
	if [ "$?" == "1" ]; then
	    testType="HRTBT"
	fi

        pv=$rootPv":"$testType"_L_UNLH"
        if [ "$verbose" == "True" ]; then
            echo "Unlatching "$pv
	fi
        putPv $pv "1"

        pv=$rootPv":"$testType"_L_UNLH"
        if [ "$verbose" == "True" ]; then
            echo "Unlatching "$pv
	fi
        putPv $pv "1"

        pv=$rootPv":"$testType"_H_UNLH"
        if [ "$verbose" == "True" ]; then
            echo "Unlatching "$pv
	fi
        putPv $pv "1"

        pv=$rootPv":"$testType"_1_H_UNLH"
        if [ "$verbose" == "True" ]; then
            echo "Unlatching "$pv
	fi
        putPv $pv "1"
    fi
    
    if [ "$pedOnly" == "True" -o "$allTests" == "True" ]; then
        pv=$rootPv":PED_L_UNLH"
        if [ "$verbose" == "True" ]; then
            echo "Unlatching "$pv
	fi
        putPv $pv "1"

        pv=$rootPv":PED_H_UNLH"
        if [ "$verbose" == "True" ]; then
            echo "Unlatching "$pv
	fi
        putPv $pv "1"
    fi
}
    

function testThreshold {
    thresPv=$1
    thres=$2
    statePv=$3
    stateGoodMsg=$4
    stateGood=$5
    stateBadMsg=$6
    stateBad=$7
    retries=$8
    verbose=$9

    # Try multiple times in case of failure
    for i in {1..10}; do
	putPv $thresPv $thres
	if [ "$?" == 1 ]; then
	    return 1
	fi	
	
        # Wait for new threshold to take effect
	usleep 500000
	
	getPv $statePv
	if [ "$?" == 1 ]; then
	    return 1
	fi
	currentState=$pvValue
	
	if [ "$currentState" == "$stateGood" ]; then
	    if [ "$verbose" == "True" ]; then
		echo " $stateGoodMsg"
	    fi
	    return 0
	else
	    if [ "$verbose" == "True" ]; then
		echo -n "."
	    fi
	fi
    done
    if [ "$verbose" == "True" ]; then
	echo " $stateBadMsg"
    fi
    return 1
}

function testChannel {
    rootPv=$1
    thresPv=$2
    lossPv=$3
    type=$4
    verbose=$5
    suffix=$6
    
    getPv $lossPv
    if [ "$?" == 1 ]; then
	return 1
    fi
    currentLoss=$pvValue

    getPv $thresPv
    if [ "$?" == 1 ]; then
	return 1
    fi
    currentThreshold=$pvValue

    if [ "$verbose" == "True" ]; then
	echo "==== "$rootPv" "$type" threshold ("$suffix") ====" 
	echo "Currest loss:      "$currentLoss
	echo "Current threshold: "$currentThreshold
    fi

    if [ "$type" == "high" ]; then
	thresBad=`echo $currentLoss - 1 | bc -l`
	thresGood=`echo $currentLoss + 1 | bc -l`
	linkProcessorCurrentState=$rootPv":"$suffix"_H_MPSC"
    else
	thresBad=`echo $currentLoss + 1 | bc -l`
	thresGood=`echo $currentLoss - 1 | bc -l`
	linkProcessorCurrentState=$rootPv":"$suffix"_L_MPSC"
    fi

    # Write thresholds that don't generate faults
    if [ "$verbose" == "True" ]; then
	echo -n "Setting "$type" threshold to "$thresGood". No faults expected: "
    fi
    testThreshold $thresPv $thresGood $linkProcessorCurrentState \
                  "IS_OK" 1 "IS_EXCEEDED (FAIL)" 0 4 $verbose

    # Write thresholds that do generate faults
    if [ "$verbose" == "True" ]; then
	echo -n "Setting "$type" threshold to "$thresBad". Faults are expected: "
    fi
    testThreshold $thresPv $thresBad $linkProcessorCurrentState \
                  "IS_EXCEEDED" 0 "IS_OK (FAIL)" 1 4 $verbose

    # Restore original threshold
    putPv $thresPv $currentThreshold
    if [ "$?" == 1 ]; then
	echo "Failed to restore threshold: "$thresPv" <= "$currentThreshold
	return 1
    fi	
}

function testAllChannels {
    rootPv=$1
    verbose=$2
    lossOnly=$3
    pedOnly=$4
    testOnly=$5
    allTests=$6

    # Loss Tests
    if [ "$lossOnly" == "True" -o "$allTests" == "True" ]; then
        # Low Test
	thresPV="$rootPv:LOSS_L"
	lossPv="$rootPv:LOSS"
	type="low"
	testChannel $rootPv $thresPV $lossPv $type $verbose "LOSS"
	if [ "$?" == 1 ]; then
	    echo "Failed on LOW threshold test."
	    return 1
	fi

        # High Test
	thresPV="$rootPv:LOSS_H"
	lossPv="$rootPv:LOSS"
	type="high"
	testChannel $rootPv $thresPV $lossPv $type $verbose "LOSS"
	if [ "$?" == 1 ]; then
	    echo "Failed on HIGH threshold test."
	    return 1
	fi
    fi

    # PED Tests
    if [ "$pedOnly" == "True" -o "$allTests" == "True" ]; then
        # Low Test
	thresPV="$rootPv:PED_L"
	lossPv="$rootPv:LOSS"
	type="low"
	testChannel $rootPv $thresPV $lossPv $type $verbose "PED"
	if [ "$?" == 1 ]; then
	    echo "Failed on LOW threshold PED test."
	    return 1
	fi

        # High Test
	thresPV="$rootPv:PED_H"
	lossPv="$rootPv:LOSS"
	type="high"
	testChannel $rootPv $thresPV $lossPv $type $verbose "PED"
	if [ "$?" == 1 ]; then
	    echo "Failed on HIGH threshold PED test."
	    return 1
	fi
    fi

    # TEST Tests
    if [ "$testOnly" == "True" -o "$allTests" == "True" ]; then
	testType="TEST"
	# Check if PV exists
	`cainfo -w 10 $rootPv:TEST_L 2>&1 | grep Native | grep TYPENOTCONN &> /dev/null`
	if [ "$?" == "1" ]; then
	    testType="TEST"
	fi

	`cainfo -w 10 $rootPv:TIMING_L 2>&1 | grep Native | grep TYPENOTCONN &> /dev/null`
	if [ "$?" == "1" ]; then
	    testType="TIMING"
	fi

	`cainfo -w 10 $rootPv:HRTBT_L 2>&1 | grep Native | grep TYPENOTCONN &> /dev/null`
	if [ "$?" == "1" ]; then
	    testType="HRTBT"
	fi

        # Low Test
	thresPV="$rootPv:"$testType"_L"
	lossPv="$rootPv:LOSS"
	type="low"
	testChannel $rootPv $thresPV $lossPv $type $verbose $testType
	if [ "$?" == 1 ]; then
	    echo "Failed on LOW threshold TEST test."
	    return 1
	fi

        # High Test
	thresPV="$rootPv:"$testType"_H"
	lossPv="$rootPv:LOSS"
	type="high"
	testChannel $rootPv $thresPV $lossPv $type $verbose $testType
	if [ "$?" == 1 ]; then
	    echo "Failed on HIGH threshold TEST test."
	    return 1
	fi
    fi
    return 0
}

# Default options
fileName=""
channel=""
verbose="False"
lossOnly="False"
pedOnly="False"
testOnly="False"
allTests="False"
unlatch="False"

while getopts ":vf:hc:lptU" opt; do
    case $opt in
	U)
	    unlatch="True"
	    ;;
        v)
            verbose="True"
            ;;
        f)
            fileName=$OPTARG
            ;;
	c)
	    channel=$OPTARG
	    ;;
	l)
	    lossOnly="True"
	    ;;
	p)
	    pedOnly="True"
	    ;;
	t)
	    testOnly="True"
	    ;;
        h)
            printUsage $0
            exit 0
            ;;
        \?)
            echo "Invalid option: -$OPTARG"
            ;;
        :)
            echo "Option -$OPTARG requires an argument."
            exit -1
            ;;
    esac
done

if [ "$lossOnly" == "False" -a "$pedOnly" == "False" -a "$testOnly" == "False" ]; then
    allTests="True"
fi
	
failCounter=0
if [ "$channel" != "" ]; then
    rootPv=`echo $channel | tr -d ' '`
    if [ "$unlatch" == "True" ]; then
	unlatchChannels $rootPv $verbose $lossOnly $pedOnly $testOnly $allTests
	exit 0
    fi
    testAllChannels $rootPv $verbose $lossOnly $pedOnly $testOnly $allTests
    if [ "$?" != 0 ]; then
	failedChannels[0]=$rootPv
	failCounter=`expr $failCounter + 1`
    fi
fi

if [ "$fileName" != "" ]; then
    if [ -a $fileName ]; then
	exec<$fileName
	lineNumber=0
	while read line; do
	    lineNumber=`expr $lineNumber + 1`
	    rootPv=`echo $line | tr -d ' '`
	    if [ "$unlatch" == "True" ]; then
		unlatchChannels $rootPv $verbose $lossOnly $pedOnly $testOnly $allTests
	    else
		testAllChannels $rootPv $verbose $lossOnly $pedOnly $testOnly $allTests
		if [ "$?" != 0 ]; then
		    failedChannels[$failCounter]=$rootPv
		    failCounter=`expr $failCounter + 1`
		fi
	    fi
	done
    fi
fi

if [ "$failCounter" != 0 ]; then
    echo "==== Test failed for these channels:"
    for c in "${failedChannels[@]}"; do
	echo $c
    done
else
    echo "==== PASSED"
fi