#!/bin/sh
#############################################################
# This script programs agcio COM4 boards
# COM4 has four RS232/RS485 ports
# We need to program eeprom to enable RS485.
#############################################################
path="${0%/*}"
. "$path/inc/gwhw.inc"

needRoot

testcmd2 ftdi_eeprom
#############################################################
# Turn ON 
$GPIO -es PERIF_USB_PWR
# wait for devices to come up
sleep 2

isConfigured() {
	[ -r "/tmp/com4_eeprom.${1}.bin" ] || return 1
	strings -n1 "/tmp/com4_eeprom.${1}.bin" | tr -d '\n' | grep -Fq -- "COM4-${1}"
}

flashCOM4() {
	# $1: device index
	# ftdi_eeprom has a bug in finding device by serial (s:0x0403:0x6011:COM4-0) with multiple devices.
	# Works correctly only when both device have been brogrammed.
	# Using index does not have this issue.
	rm "/tmp/com4_eeprom.${1}.bin" 2>/dev/null
	if ftdi_eeprom --read-eeprom --device i:0x0403:0x6011:${1} "$path/bin/agc_com4_ftdi.${1}.conf"; then
		if isConfigured "${1}"; then
			echo "COM4-${1} FTDI is configured"
		else
			# most likely not programmed
			echo "COM4-${1} FTDI start flashing"
			if ftdi_eeprom --flash-eeprom --device i:0x0403:0x6011:${1} "$path/bin/agc_com4_ftdi.${1}.conf"; then
				echo "COM4-${1} FTDI flashing OK"
			else
				echo "COM4-${1} FTDI flashing FAILED"
			fi
		fi
	else
		echo "COM4-${1} not found"
	fi
}

flashCOM4 0
flashCOM4 1

echo "Reset COM4 board power"
# Reset COM4 board, for changes to take effect and to get serial ports back
$GPIO -t PERIF_USB_PWR OFFON
