#!/bin/sh

# Linux GPIOs on XBee lines
XBEE_RESET_N_GPIO="##XBEE_RESET_N_GPIO##"
XBEE_SLEEP_RQ_GPIO="##XBEE_SLEEP_RQ_GPIO##"

xbee_init() {
	# Set low XBEE_SLEEP_RQ
	gpioset ${3} ${4}=0

	# Power cycle XBEE_RESET_N
	gpioset ${1} ${2}=0
	gpioset ${1} ${2}=1
}

xbee_iterate_list() {
	i=0
	for RESET in $(echo ${XBEE_RESET_N_GPIO} | sed "s/,/ /g"); do
		j=0
		for SLEEP in $(echo ${XBEE_SLEEP_RQ_GPIO} | sed "s/,/ /g"); do
			if [ "${i}" = "${j}" ]; then
				if [ "${1}" = "start" ]; then
					xbee_init $(echo ${RESET} | sed "s/@/ /g") $(echo ${SLEEP} | sed "s/@/ /g")
				fi
			fi
			j="$((j + 1))"
		done
		i="$((i + 1))"
	done
}

case "$1" in
	start)
		echo -n "Starting XBee hardware: "
		xbee_iterate_list start
		echo "done."
		;;
	stop)
		;;
	restart)
		$0 stop
		sleep 1
		$0 start
		;;
	*)
		echo "Usage: $0 {start|stop|restart}"
		exit 1
		;;
esac
