#!/bin/bash

# Arch Linux ARM
# Seagate GoFlex Net U-Boot Installer

cd /tmp

function msg { printf "%25s" "$@"; }
function try {
  "$@"
  if [[ $? != 0 ]]; then
    echo " [FAILED]"
    echo ""
    echo "Failed to install U-Boot. DO NOT REBOOT"
    echo "Please seek assistance at:"
    echo "  http://archlinuxarm.org/forum"
    echo "  #archlinux-arm on irc.freenode.net"
    exit 1
  fi
  return $status
}

echo ""
echo "Downloading flash utilities.."
for file in blparam flash_erase fw_printenv nanddump nandwrite; do
  msg ${file}
  rm -f ${file}{,.md5}
  try wget -q http://os.archlinuxarm.org/os/pogoplug/${file}
  try wget -q http://os.archlinuxarm.org/os/pogoplug/${file}.md5
  try md5sum -cs ${file}.md5
  echo " [OK]"
  chmod +x ${file}
done


echo ""
echo "Downloading U-Boot and environment.."
for file in uboot-goflexnet.kwb uboot-goflexnet.env; do
  msg ${file}
  rm -f ${file}{,.md5}
  try wget -q http://os.archlinuxarm.org/os/armv5te/boot/goflexnet/${file}
  try wget -q http://os.archlinuxarm.org/os/armv5te/boot/goflexnet/${file}.md5
  try md5sum -cs ${file}.md5
  echo " [OK]"
done

echo ""
echo "Installing.."
msg "saving MAC address"
mac=$(/tmp/blparam | grep ethaddr | cut -d= -f2)
if [[ $mac == '' ]]; then echo " [FAILED]"; exit 1; fi
echo " [$mac]"

msg "erasing U-Boot NAND"
try /tmp/flash_erase /dev/mtd0 0 4 > /dev/null
echo " [OK]"

msg "erasing environment"
try /tmp/flash_erase /dev/mtd0 0xc0000 1 > /dev/null
echo " [OK]"

msg "writing U-Boot"
try /tmp/nandwrite /dev/mtd0 uboot-goflexnet.kwb > /dev/null
echo " [OK]"

msg "writing environment"
try /tmp/nandwrite -s 0xc0000 /dev/mtd0 uboot-goflexnet.env > /dev/null
echo " [OK]"

echo ""
echo "Validating.."
/tmp/nanddump -nol 0x80000 -f /tmp/uboot-goflexnet.kwb /dev/mtd0
/tmp/nanddump -nol 0x20000 -s 0xc0000 -f /tmp/uboot-goflexnet.env /dev/mtd0

echo ""
msg "checking U-Boot"
try md5sum -cs uboot-goflexnet.kwb.md5
echo " [OK]"

msg "checking environment"
try md5sum -cs uboot-goflexnet.env.md5
echo " [OK]"

msg "setting MAC"
ln -s fw_printenv fw_setenv
mount -o remount,rw /
try echo "/dev/mtd0 0xc0000 0x20000 0x20000" > /etc/fw_env.config
mount -o remount,ro /
/tmp/fw_setenv ethaddr ${mac}
echo " [OK]"

echo ""
echo "U-Boot has been installed successfully."
echo ""
