#!/bin/bash

#########################################
# Name: gwstart
#
# Summary: Aggregate gateway startup tasks
#
# Description: Initialize virtual serial port(s)
#   - power sensor nodes
#   - start sds and sbr services
#   - run gateway
#
# Author: k. headley
#
# Copyright 2015 MBARI
#
#########################################

#########################################
# Script configuration defaults
# casual users should not need to change
# anything below this section
#########################################
description="[Gateway quick start]"

DIGI_CMD="sudo ${XFHOME}/src/scripts/digicfg"
SNPOW_CMD="gwdio -s all:H"

#declare -a MEH_HOST=( 134.89.13.14 134.89.13.38 )
declare -a MEH_HOST=( 134.89.91.33 134.89.91.65 )
declare -a DEP_DIR=( /home/ops/swfoce /home/ops/swfoce )
declare -a GWS_OPS

#################################
# Script variable initialization
#################################
VERBOSE="N"
unset GWS_ID
unset GWS_CONF

#################################
# Function Definitions
#################################
#################################
# name: sigTrap
# description: signal trap callback
# will interrupt 
# args: none
#################################
sigTrap(){
    exit 0;
}

#################################
# name: printUsage
# description: print use message
# args: none
#################################
printUsage(){
    echo
    echo "Description: ${description}"
    echo
    echo "usage: `basename $0` -g <n> -f <file> [options]"
	echo "Options:"
    echo "-i <n>    : gateway index [0:1]"
    echo "-f <file> : config file"
    echo "-L        : list configs"
    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}" == "Y" ] || [ "${VERBOSE}" == "TRUE" ]
    then
	echo "$1" >&2
    fi
}

########################################
# name: imsg
# description: echos with indent
# args:
#     msg: message
#  indent: indent level
########################################
imsg(){
  OIFS=$IFS
  IFS=""
  msg_pad="                                        "
  let "msg_indent=${1}"
  shift
  all="${@}"
  printf "%s%s\n" ${msg_pad:0:${msg_indent}} ${all}
  IFS=$OIFS
}

########################################
# name: msg
# description: echos with default indent
# args:
#     msg: message
########################################
msg(){
 imsg $MSG_INDENT "${*}"
}

########################################
# 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 i:f:LhV Option
	do
		vout "processing $Option[$OPTARG]"
		case $Option in
            i ) GWS_ID=$OPTARG
                GWS_OPS[${#GWS_OPS[*]}]="start"
            ;;
            f ) GWS_CONF=$OPTARG
            ;;
            L )
                GWS_OPS[${#GWS_OPS[*]}]="list"
            ;;
			V ) VERBOSE="TRUE"
			;;
			h)printUsage
				exit 0
			;;
			*) exit 0 # getopts outputs error message
			;;
		esac
	done
}

########################################
# name: validateArgs
# description: validate arguments
# args:
#     args:       none
#     returnCode: none
########################################
validateArgs(){
    if [ ${#MEH_HOST[*]} -ne ${#DEP_DIR[*]} ]
    then
        exitError "config array size mismatch" 1
    fi

#    if [ ! "${GWS_CONF}" ] || [ ! "${GWS_ID}" ]
#    then
#    exitError "-g and -f are required" 1
#    fi

    if [ "${GWS_ID}" ]
    then
    if [ "${GWS_ID}" -ge "${#MEH_HOST[@]}" ] || [ "${GWS_ID}" -ge "${#DEP_DIR[@]}" ]
    then
        let "max=${#MEH_HOST[*]}-1"
        exitError "invalid gateway index [id <= $max]" 1
    fi
    fi

#    if [ ! -f "${GWS_CONF}" ]
#    then
#        exitError "config file not found [$GWS_CONF]" 1
#    fi
#
#    if [ ! -f "${DEP_DIR[$GWS_ID]}" ]
#    then
#        exitError "config file not found [${DEP_DIR[$GWS_ID]}]" 1
#    fi

}

########################################
# name: listConfig
# description: list configured options
# args:
#     args:       positional paramters
#     returnCode: none
########################################
listConfig(){
    let "i=0"
    echo
    echo "XFHOME    : [${XFHOME}]"
    echo "DIGI_CMD  : [${DIGI_CMD}]"
    echo "SNPOW_CMD : [${SNPOW_CMD}]"
    echo
    echo "[id]: Deployment MEH-Host"
    while [ "${i}" -lt "${#MEH_HOST[@]}" ]
    do
        echo "[$i]: ${DEP_DIR[$i]} ${MEH_HOST[$i]}"
        let "i++"
    done
    echo
}

########################################
# name: startGW
# description: start gateway and related services
# args:
#     args:       positional paramters
#     returnCode: none
########################################
startGW(){
    echo "configuring MEH virtual serial port [${MEH_HOST[$GWS_ID]}]"
    ${DIGI_CMD} -a ${MEH_HOST[$GWS_ID]} -i ME -c init
    sleep 2
    ${SNPOW_CMD}
    sleep 2
    cd ${DEP_DIR[$GWS_ID]}
    echo "starting shared data service"
    xsvc -l logs start sds -p
    sleep 2
    echo "starting service broker"
    xsvc -l logs start sbr
    sleep 2
    echo "starting gateway using ${GWS_CONF}"
    xsvc -l logs start gw -f ${GWS_CONF} -a arch
}

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


# Argument processing
# Accepts arguments from command line 
# or pipe/file redirect
# Comand line settings override config
# file settings

if [ -t 0 ]
then
	if [ "$#" -eq 0 ]
    then
		printUsage
		exit -1
	else
		processCmdLine $*
		let "i=$OPTIND-1"
		#while [ "${i}" -gt 0  ]
		#do
		#	shift
		#	let "i-=1"
		#done
	fi
fi

vout "GWS_ID   : [${GWS_ID}]"
vout "GWS_CONF : [${GWS_CONF}]"
vout "VERBOSE  : [${VERBOSE}]"

validateArgs

for op in ${GWS_OPS[@]}
do
    if [ "${op}" == "list" ]
    then
        listConfig
    elif [ "${op}" == "start" ]
    then
        startGW
    else
        echo "invalid op [$op]"
    fi

done
