#!/bin/sh

if [[ ! -e /dev/mtd0 ]]; then
    echo '>> Error: /dev/mtd0 does not exist.'
    return
fi

# set up config for fw_printenv/setenv
echo '/dev/mtd0 0x20000 0x10000 0x10000' > /etc/fw_env.config

# save MAC address
mac=$(fw_printenv | grep ethaddr | cut -d= -f2)
if [[ $mac == '' ]]; then
   echo '>> Error: Could not find MAC address from current U-Boot.'
   return
fi

mac1=$(fw_printenv | grep eth1addr | cut -d= -f2)
if [[ $mac1 == '' ]]; then
   echo '>> Error: Could not find second MAC address from current U-Boot.'
   return
fi

echo "Found MACs ${mac} and ${mac1}"

# flash U-Boot
echo "Erasing u-boot sectors..."
flash_erase /dev/mtd0 0x40000 20

echo "Writing u-boot to flash..."
dd if=/boot/u-boot.bin of=/dev/mtd0 bs=64K seek=4 status=progress

echo "Writing u-boot environment..."
fw_setenv -s /boot/u-boot.env

echo "Setting MAC addresses.."
fw_setenv ethaddr ${mac}
fw_setenv eth1addr ${mac1}

fw_printenv

echo "So, there you have it"
