#!/bin/bash

SERV_HOME=$(dirname $0)
. ${SERV_HOME}/iotg-rpi4-functions

MIN_OFFSET=0
MAX_OFFSET=3

IO_GPIO_CHIP=0
declare -a GPIO_ab_o=(0 1 2 3)
declare -a GPIO_ab_i=(4 5 6 7)
declare -a GPIO_cd_o=(8 9 10 11)
declare -a GPIO_cd_i=(18 19 20 21)

function msg() {
	echo "${SCR_NAME}: $@"
}

function err_msg() {
	msg "Error: $@"
	exit 1
}

function usage() {
	local ret=${1:-0}
	echo "Usage: ${SCR_NAME} [options] <command>"
	echo "Command:"
	echo "	-i <offset>			read state of input pin <0|1|2|3>"
	echo "	-o <offset> <state>		set output pin <0|1|2|3> state <0|1>"

	echo "Options:"
	echo "	-s <slot>			dual slot name <ab|cd>"

	echo "	-h				display this help"
	exit ${ret}
}

function main() {
	local slot=
	local offset=
	local opt=
	local state=
	while getopts ':hs:i:o:' OPTION; do
		case "${OPTION}" in
		"s")
			slot="${OPTARG,,}"
			case "${slot}" in
			"ab" | "cd")
				;;
			*)
				err_msg "Invalid slot ${OPTARG}"
				;;
			esac
			get_ie_type ${slot} || err_msg "Cannot read I/O module type in [${slot^^}] slot"
			if [[ "${DUAL_IE_DETECTED[${slot}]}" != "IO" ]]; then
				err_msg "IO module not detected in [${slot^^}] slot"
			fi
			;;
		"i" | "o")
			opt=${OPTION}
			offset="${OPTARG}"
			if [[ ${offset} -lt ${MIN_OFFSET} || ${offset} -gt ${MAX_OFFSET} ]]; then
				err_msg "Invalid I/O pin offset ${offset}"
			fi
			;;
		"h")
			usage 0
			;;
		?)
			usage 1
			;;
		esac
	done
	if [[ -z "${slot}" ]]; then
		err_msg "Slot patameter not specified"
	fi
	if [[ -z "${offset}" ]]; then
		err_msg "Offset patameter not specified"
	fi

	declare -n arr_name=GPIO_${slot}_${opt}
	gpio_num=${arr_name[${offset}]}
	case "${opt}" in
	"i")
		state=$(gpioget ${IO_GPIO_CHIP} ${gpio_num})
		ret=$?
		[[ ${ret} -ne 0 ]] || echo ${state}
		return ${ret}
		;;
	"o")
		shift "$((${OPTIND} - 1))"
		state=${1:-}
		if [[ -z "${state}" ]]; then
			err_msg "State patameter not specified"
		fi
		if [[ ${state} -lt 0 || ${state} -gt 1 ]]; then
			err_msg "Invalid state ${state}"
		fi
		gpioset ${IO_GPIO_CHIP} ${gpio_num}=${state}
		return $?
		;;
	*)
		return 1
		;;
	esac
}

#set -x
SCR_NAME=$(basename $0)
main $@
#set +x
