#!/bin/bash

#########################################
# Name: snltest
#
# Summary: run sensor node loopback test
#
# Description: cycle sensor node power
#   and run loopback test on snports
#
# Author: k. headley
#
# Copyright 2015 MBARI
#
#########################################

#########################################
# Script configuration defaults
# casual users should not need to change
# anything below this section
#########################################
description="[run sensor node loopback test]"

PERIOD_SEC=30
#SNPORT=0
DFL_NCYCLES=-1
DFL_PORTS="-p 0,38400 -p 1,38400 -p 2,38400"
DFL_LOOP_CFG="-l 10,64,100,500"
#TTY=/dev/ttyO1
GWSN_ON="-1 0,1,2"
GWSN_OFF="-0 0,1,2"
# for a previous version of gwsn
#GWSN_ON="-n 0,1,2"
#GWSN_OFF="-f 0,1,2"
DFL_CFG="snltest.conf"

declare -a SNPORT=( 0 -1 -1 -1 )
declare -a TTY=( "/dev/ttyO1" "/dev/ttyO2" "/dev/ttyO4" "/dev/ttyO5" )
declare -a PORTS=( "$DFL_PORTS" "$DFL_PORTS" "$DFL_PORTS" "$DFL_PORTS"  )
declare -a LOOP_CFG=( "$DFL_LOOP_CFG" "$DFL_LOOP_CFG" "$DFL_LOOP_CFG" "$DFL_LOOP_CFG" )
declare -a NODE=( "node0" "node1" "node2" "node3" )

CFG_FILE=$DFL_CFG

unset TEST
#unset NODE
#unset PORTS
NCYCLES=-1
#################################
# Script variable initialization
#################################
VERBOSE="FALSE"

#################################
# Function Definitions
#################################

#################################
# name: printUsage
# description: print use message
# args: none
#################################
printUsage(){
    echo
    echo "Description: $description"
    echo
    echo "usage: `basename $0` [options]"
    echo " Options:"
    echo "  -n <cycles> : n cycles                [$DFL_NCYCLES]"
    echo "  -c <cycle>  : cycle time (sec)        [$PERIOD_SEC]"
echo "  -f <file> : config file                [$DFL_CFG]"
# echo "  -t <device> : snode host port      [$TTY]"
#    echo "  -s <snode,device>  : sensor node port and tty device"
#    echo "  -l <sn,n,b,wr,c,aen,ben>: loop config [$DFL_LOOP_CFG]"
#    echo "  -p <node,port,baud> : add port(s)     [$DFL_PORTS]"
echo "  -T             : test mode       [$TEST]"
echo "  -v             : verbose output       [$VERBOSE]"
    echo "  -h             : print use message"
    echo ""
    echo
}

########################################
# name: vout
# description: print verbose message to stderr
# args:
#     msg: message
########################################
vout(){
    if [ "$VERBOSE" == "TRUE" ]
    then
        echo "$1" >&2
    fi
}

########################################
# name: exitError
# description: print use message to stderr
# args:
#     msg:        error message
#     returnCode: exit status to return
########################################
exitError(){
    echo >&2
    echo "`basename $0`: error - $1" >&2
    echo >&2
    exit $2
}

########################################
# name: processCmdLine
# description: do command line processsing
# args:
#     args:       positional paramters
#     returnCode: none
########################################
processCmdLine(){
    OPTIND=1
    vout "`basename $0` all args[$*]"

while getopts c:f:l:n:p:s:Thv Option
    do
        #vout "processing $Option[$OPTARG]"
        case $Option in
            c ) PERIOD_SEC=$OPTARG
            ;;
            n ) NCYCLES=$OPTARG
            ;;
            f) CFG_FILE=$OPTARG
            ;;
            s ) SNPORT="$OPTARG"
                local testsnp
                local testtty
                OIFS=$IFS
                IFS=',' read testsnp testtty <<< ${OPTARG}
                IFS=$OIFS
                if [ "$testsnp" -ge 0 ] && [ "$testsnp" -le 3 ]
                then
                    if [ -e "$testtty" ]
                    then
                    SNPORT[$testsnp]=$testsnp
                    TTY[$testsnp]=$testtty
                    fi
                fi
            ;;
            l ) LOOP_CFG="-l $OPTARG"
                local testsn
                local testcfg
                OIFS=$IFS
                IFS=',' read testsn testcfg <<< ${OPTARG}
                IFS=$OIFS
                if [ "$testsn" -ge 0 ] && [ "$testsn" -le 3 ]
                then
                LOOP_CFG[$testsn]="-l $testcfg"
                fi
            ;;
            p ) PORTS="$PORTS -p $OPTARG"
                local testsn
                local testport
                OIFS=$IFS
                IFS=',' read testsn testport <<< ${OPTARG}
                IFS=$OIFS
                if [ "$testsn" -ge 0 ] && [ "$testsn" -le 3 ]
                then
                PORTS[$testsn]="$PORTS[$testsn] -p $testport"
                fi
            ;;
T ) TEST="echo "
;;
v ) VERBOSE="TRUE"
;;
            h) printUsage
            exit 0
            ;;
            *) exit 0 # getopts outputs error message
            ;;
        esac
    done
}

##########################
# Script main entry point
##########################


processCmdLine $*
let "i=$OPTIND-1"
#while [ "${i}" -gt 0  ]
#do
#	shift
#	let "i-=1"
#done
#fi

# finish variable initialization/validation

# Argument processing
# Accepts arguments from command line
if [ -f "$CFG_FILE" ]
then
. $CFG_FILE
else
vout "Warning: could not find configuration [$CFG_FILE]"
fi

NODE[0]="node0"
NODE[1]="node1"
NODE[2]="node2"
NODE[3]="node3"

cycle=1
let "loop_end=$NCYCLES+1"

vout "PERIOD_SEC [$PERIOD_SEC]"
vout "NCYCLES    [$NCYCLES]"
vout "NODE       [${NODE[*]}]"
vout "TTY        [${TTY[*]}]"
vout "PORTS      [${PORTS[*]}]"
vout "LOOP_CFG   [${LOOP_CFG[*]}]"
vout "VERBOSE    [$VERBOSE]"


while [ "${cycle}" -ne "$loop_end" ]
do

    echo "###### `date` [$cycle/$NCYCLES]######"

    for snp in `echo ${SNPORT[*]}`
    do
        if [ "$snp" -ge 0 ]
        then
            # snode port ON
            if [ $TEST ]
            then
                $TEST "gwdio -s ${NODE[$snp]}:1 &> /dev/null"
            else
                gwdio -s ${NODE[$snp]}:1 &> /dev/null
            fi
            $TEST sleep 1

            # snport power ON
            $TEST gwsn -s $snp,${TTY[$snp]} $GWSN_ON -b 2
            $TEST sleep 1

            # run loopback test
            if [ $TEST ]
            then
                $TEST "snloop -s ${TTY[$snp]}  ${PORTS[$snp]} ${LOOP_CFG[$snp]} &> /dev/null"
                $TEST test=$?
                $TEST echo "snloop [$snp] returned [$test]"
            else
                snloop -s ${TTY[$snp]}  ${PORTS[$snp]} ${LOOP_CFG[$snp]} &> /dev/null
                test=$?
                echo "snloop [$snp] returned [$test]"
            fi

            # snport power OFF
            $TEST gwsn -s $snp,${TTY[$snp]} $GWSN_OFF  -b 0
            $TEST sleep 1

            # snode port OFF
            if [ $TEST ]
            then
                $TEST gwdio -s ${NODE[$snp]}:0 &> /dev/null
            else
                gwdio -s ${NODE[$snp]}:0 &> /dev/null
            fi
        fi
    done

    let "cycle=$cycle+1"

    # delay until next cycle
    $TEST sleep $PERIOD_SEC

done
