#!/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. PICM:IN20:665)"
    echo "  -c <channel>: test one channel (PED,TEST,LOSS)"
    echo ""
    echo "Examples:"
    echo "   $0 -f LN37.dat"
    echo "   $0 -c PICM:IN20:665"
    echo "   $0 -u -c PICM:IN20:665"
    echo "   $0 -U -c PICM:IN20:665"
    echo "   $0 -U -f LN11.dat"
}

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

    pv=$rootPv":LOSSL_UNLH" 
    if [ "$verbose" == "True" ]; then
	echo "Unlatching "$pv
    fi
    putPv $pv "1"
    
    pv=$rootPv":LOSS1L_UNLH" 
    if [ "$verbose" == "True" ]; then
	echo "Unlatching "$pv
    fi
    putPv $pv "1"
    
    pv=$rootPv":LOSS10L_UNLH" 
    if [ "$verbose" == "True" ]; then
	echo "Unlatching "$pv
    fi
    putPv $pv "1"
    
    pv=$rootPv":LOSS30L_UNLH" 
    if [ "$verbose" == "True" ]; then
	echo "Unlatching "$pv
    fi
    putPv $pv "1"
    
    pv=$rootPv":LOSS60L_UNLH" 
    if [ "$verbose" == "True" ]; then
	echo "Unlatching "$pv
    fi
    putPv $pv "1"
    
    pv=$rootPv":LOSSH_UNLH" 
    if [ "$verbose" == "True" ]; then
	echo "Unlatching "$pv
    fi
    putPv $pv "1"
    
    pv=$rootPv":LOSS1H_UNLH" 
    if [ "$verbose" == "True" ]; then
	echo "Unlatching "$pv
    fi
    putPv $pv "1"
    
    pv=$rootPv":LOSS10H_UNLH" 
    if [ "$verbose" == "True" ]; then
	echo "Unlatching "$pv
    fi
    putPv $pv "1"
    
    pv=$rootPv":LOSS30H_UNLH" 
    if [ "$verbose" == "True" ]; then
	echo "Unlatching "$pv
    fi
    putPv $pv "1"
    
    pv=$rootPv":LOSS60H_UNLH" 
    if [ "$verbose" == "True" ]; then
	echo "Unlatching "$pv
    fi
    putPv $pv "1"
}
    

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

     # Low Test
    thresPV="$rootPv:P1_LOSS_L"
    lossPv="$rootPv:P1_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:P1_LOSS_H"
    lossPv="$rootPv:P1_LOSS"
    type="high"
    testChannel $rootPv $thresPV $lossPv $type $verbose "LOSS"
    if [ "$?" == 1 ]; then
	echo "Failed on HIGH threshold test."
	return 1
    fi

    return 0
}

# Default options
fileName=""
channel=""
verbose="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
	    ;;
        h)
            printUsage $0
            exit 0
            ;;
        \?)
            echo "Invalid option: -$OPTARG"
            ;;
        :)
            echo "Option -$OPTARG requires an argument."
            exit -1
            ;;
    esac
done

failCounter=0
if [ "$channel" != "" ]; then
    rootPv=`echo $channel | tr -d ' '`
    if [ "$unlatch" == "True" ]; then
	unlatchChannels $rootPv $verbose
	exit 0
    fi
    testAllChannels $rootPv $verbose
    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
	    else
		testAllChannels $rootPv $verbose
		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