#!/bin/bash
#########################################
# Name: xfoce-init-gpio
#
# Summary: perform HW init not handled by
#          uboot; Called by systemd init
#
# Description:
#
# Author: kheadley
#
# Copyright MBARI 2014
#
#########################################

#################################
# Script variable initialization
#################################
description="xFOCE gateway boot-time GPIO init"
VERBOSE="N"
OP="INIT"

let "EXIT_CODE=0"
let "ERR_COUNT=0"

#################################
# name: printUsage
# description: print use message
# args: none
#################################
printUsage(){
    echo
    echo " Description: $description"
    echo
    echo " usage: `basename $0` [options]"
    echo " Options:"
    echo "  -I : Initialize"
    echo "  -U : Un-initialize"
    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" ] || [ "$VERBOSE" == "Y" ]
    then
	echo "$1" >&2
    fi
}

########################################
# name: chk_stat
# description: check value and update exit code
# args:
#     msg: message
########################################
chk_stat(){
    if [ "$1" -ne 0 ]
    then
	  let "EXIT_CODE|=(1 << $ERR_COUNT)"
	  let "ERR_COUNT+=1"
    fi
}

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


# Argument processing
while getopts IUhV Option
do
	vout "processing $Option[$OPTARG]"
	case $Option in
		I ) OP="INIT" 
		;;
		U ) OP="UINIT" 
		;;
        h )printUsage
        exit 0
        ;;
        V ) VERBOSE="Y"
        ;;
	esac
done

XFHOME=/home/ops/xfoce
. $XFHOME/src/scripts/xfenv $XFHOME

if [ "${OP}" == "INIT" ]
then

# set up GPIO directions/levels
${XFHOME}/src/gateway/apps/gwgpio -I 
x=$?
chk_stat $x
echo "gwgpio -I returned $x"

${XFHOME}/src/gateway/apps/gwdio -s all:0
x=$?
chk_stat $x
echo "gwpio returned $x"

elif [ "${OP}" == "UINIT" ]
then

# un-export GPIO devices
/home/ops/xfoce/src/gateway/apps/gwgpio -U
x=$?
chk_stat $x
echo "gwpio -U returned $x"

fi

exit $EXIT_CODE
