#!/bin/bash

DEV=
FILE=
NEED_SUDO=0
RESET=0
FTDI_MOD=0
SERIAL=

while getopts "d:f:t:R:lrh?s:x" options
do
	case "${options}" in
		:)
			echo "missing argument for: ${OPTARG}"
			;;
		f)
			FILE=$OPTARG
			;;
		d)
			DEV=$OPTARG
			;;
		l)
			;;
		r)
			RESET=1
			;;
		R)
			;;
		t)
			;;

		s)
			SERIAL=$OPTARG
			;;
		?)
			#echo "unknown option: ${OPTARG}"
			#exit 2
			;;
		*)
			#echo "unsupported: ${OPTARG}"
			;;
	esac
done

if [[ "$DEV" =~ ttyACM ]]; then
	#echo "ConBee II specified $DEV"
	NEED_SUDO=0
elif [[ "$DEV" =~ ttyUSB ]] || [[ "$DEV" =~ ^[0-9]{1} ]]; then

	if [[ -n "$FILE" ]] || [[ $RESET -eq 1 ]]; then
		NEED_SUDO=1
		FTDI_MOD=1
	fi
	#echo "ConBee I specified $DEV, need sudo $NEED_SUDO"
elif [[ -z "$DEV" ]] && [[ -n "$FILE" || $RESET -eq 1 ]]; then
	NEED_SUDO=1
	#echo "RaspBee (default) or only serial specified, need sudo $NEED_SUDO"
fi

# only root can run this script
if [[ $NEED_SUDO -eq 1 ]] && [[ "$(id -u)" != "0" ]]; then
	echo "no super user rights, forgot sudo?"
	exit 1
fi

if [[ $FTDI_MOD -eq 1 ]]; then
	rmmod ftdi_sio
	rmmod usbserial
fi

$0.bin $@
RET=$?

if [[ $FTDI_MOD -eq 1 ]]; then
	modprobe usbserial
	modprobe ftdi_sio
fi

exit $RET
