#!/bin/bash

SCR_NAME=$(basename ${BASH_SOURCE[0]})
[[ -z ${IOTG_LIB_HOME} ]] && export IOTG_LIB_HOME=$(dirname $(readlink -e ${BASH_SOURCE[0]}))

# Includes
. ${IOTG_LIB_HOME}/common.inc
. ${IOTG_LIB_HOME}/stack_lib.inc
. ${IOTG_LIB_HOME}/dio_lib.inc

function usage() {
	local ret=${1:-0}
cat << EOF
Usage: ${SCR_NAME} [options] <offset> <state>

Set digital output state of the Digital I/O (DIO) module

Command:
 offset: output pin offset: <0..MaxOffset>
 state:  output pin state to be set: <0|1>
Options:
 -h:    display this help and exit
EOF
	exit ${ret}
}

declare -a D_CHIP=()
declare -a D_PIN=()

function main() {
	local slot=${IE_DIO_SLOT}
	local offset=
	local state=

	while getopts ':h' OPTION; do
		case "${OPTION}" in
		"h")
			usage 0
			;;
		?)
			usage 1
			;;
		esac
	done
	offset="${1:-}"
	[[ -n ${offset} ]] || err_msg "Output pin offset is missing"
	state="${2:-}"
	[[ -n ${state} ]] || err_msg "State is missing"
	[[ "${state}" =~ [0-1]  ]] || err_msg "Invalid state '${state}'"

	# Check parameters
	check_params_out ${slot} ${offset}
	# Read state
	gpioset ${LIBGPIOD_OPT} ${D_CHIP[${offset}]} ${D_PIN[${offset}]}=${state}
	return $?
}

main $@
