#!/bin/sh
#############################################################
# Writes SMSC configuration to EEPROM
# There are two options for flashing
# 1) full valid image
#    ex: gwhw flash smsc eth1 3c:39:e7:8f:ff:ff
# 2) just mac address (invalid for smsc, but valid for linux)
#    ex: gwhw flash smsc eth1 3c:39:e7:8f:ff:ff mac-only
#############################################################
path="${0%/*}"
. "$path/inc/gwhw.inc"
. "$path/inc/smsc.inc"

needRoot

usage() {
	die 'gwhw flash smsc [ETH] [MAC] [IMAGE]'
}

testcmd2 ethtool

doMinimal=true
doClean=false
doMacOnly=false
while : ; do
	case "$1" in
		-f|--f|--force|--full)
			doMinimal=false
		;;
		--)
			shift
			break
		;;
		-*)
			usage
		;;
		*)
			break
		;;
	esac
	shift
done

ETH="${1}"; shift
MAC="$(echo "${1}" | tr A-F a-f)"; shift
IMG_CUSTOM_BASE="${1}"; shift

[ -z "${ETH}" ] && usage
[ -z "${MAC}" ] && usage

[ 'clean'    = "${IMG_CUSTOM_BASE}" ] && doClean=true
[ 'mac-only' = "${IMG_CUSTOM_BASE}" ] && doMacOnly=true

#############################################################

genMAC() {
	printf "\x${1//:/'\x'}"
}

genimg() {
	img="$1" # base SMSC image
	mac="$2" # mac address to use in new image
	# First byte before MAC is always 0xA5
	printf "\xA5"
	genMAC "${mac}"
	# Rest of the bytes after MAC data
	dd if="${img}" bs=1 skip=7 2>/dev/null
}

gen7FF() {
	printf "\xFF\xFF\xFF\xFF\xFF\xFF\xFF"
}

#############################################################
# Turn ON (incorrect for GW6e)
$GPIO -es LAN_BOARD_PWR

find_smsc "${ETH}" || die "${ETH} is not a smsc device"
custom_image "${IMG_CUSTOM_BASE}"
echo "${ETH} path: ${DEV_PATH}"
echo "${ETH} image: ${IMG_BASE}"

checkEEPROM_installedW "${ETH}" || die "${ETH} may not have eeprom installed"

if $doClean; then
	# Erase configured flag and MAC address
	gen7FF | ethtool -E "${ETH}" magic 0x9500 offset 0x00 length 7 \
	|| die "${ETH} eeprom clean failed"
	exit 0
fi

isValidMAC "${MAC}"    || die "Invalid MAC provided: ${MAC}"
if $doMinimal && checkEEPROM_configured "${ETH}"; then
	if [ "${MAC}" = "${configured_mac}" ]; then
		echo "${ETH} already configured to ${configured_mac}"
		exit 0
	else
		# just update MAC portion
		echo "Changing MAC from ${configured_mac} to ${MAC}"
		doMacOnly=true
	fi
fi

if $doMacOnly; then
	# Write only MAC address portion
	genMAC "${MAC}" | ethtool -E "${ETH}" magic 0x9500 offset 0x01 length 6 \
	|| die "${ETH} MAC update failed"
	exit 0
fi

# Do full image flash
[ -r "${IMG_BASE_FULL}" ]   || die "Base image not found: ${IMG_BASE}"

genimg "${IMG_BASE_FULL}" "${MAC}" > "/tmp/${ETH}.img" \
|| die "${ETH} image generation failed"

[ "${IMG_SIZE}" = "$(wc -c "/tmp/${ETH}.img" | cut -d' ' -f1)" ] \
|| die "Generated image has wrong size"

cat "/tmp/${ETH}.img" | ethtool -E "${ETH}" magic 0x9500 offset 0x00 length "${IMG_SIZE}" \
|| die "${ETH} image write failed"


