#!/bin/sh /etc/rc.common
# Copyright (C) 2006 OpenWrt.org

START=16

_check_paths() {
	for id in $@; do
		path="/sys/bus/usb/drivers/usb/$id"
		[ ! -d $path ] && return 1
	done

	return 0
}

usbcheck_passed() {
	echo "USB system start up: OK"
	uci -q set system.usbcheck.counter='0'
	uci commit system

	return 0
}

set_tty_duplex() {
	# Configure the DUPLEX pin as an output and set it low for RS485
	# Temporary workaround until a proper fix is implemented in tlt-gpio
	output=$(gpiofind GPIO_RS485_RX_EN)

	[ -z "$output" ] && return

	gpioset $output="0"
}

boot() {
	mount_root done
	rm -f /sysupgrade.tgz && sync

	#Reset USB hub if it is not detected
	usb_id="$(jsonfilter -i /etc/board.json -e '@.usbhubcheck.usb_id')"

	if [ -n "$usb_id" ]; then
		gpio="$(jsonfilter -i /etc/board.json -e '@.usbhubcheck.gpio')"
		gpio_path="/sys/class/gpio/${gpio}/value"

		if ! _check_paths "$usb_id" && [ -f "$gpio_path" ]; then
			for count in $(seq 3); do 
				echo "USB hub not detected, resetting" > /dev/kmsg
				echo 1 > $gpio_path
				sleep 1
				echo 0 > $gpio_path
				sleep 2
				_check_paths "$usb_id" && break
			done
		fi
	fi
	set_tty_duplex

	# Reboot if usb subsystem doesn't start properly
	if [ -n "$(uci -q get system.usbcheck.path)" ]; then
		disable="$(uci -q get system.modem.disable)"
		path="$(uci -q get system.usbcheck.path)"

		if [ -z "$disable" ] || [ "$disable" -eq 0 2>/dev/null ]; then
			for i in $(seq 0 5); do
				[ -d "$path" ] && usbcheck_passed && return 0
				sleep 5
			done

			echo "USB system start up FAILED"
			cnt=$(uci -q get system.usbcheck.counter)
			max=$(uci -q get system.usbcheck.max)

			if [ "$max" -gt "$cnt" ]; then
				cnt=$((cnt+1))
				uci -q set system.usbcheck.counter=$cnt
				uci commit system
				echo "Rebooting..."
				sync && reboot -f
			fi
		else
			usbcheck_passed
		fi
	fi
}
