#!/bin/sh -e
if [ "$1" = -u ]; then
    NN=
else
    if [ "${1#usb}" = "$1" ]; then
	if ! ping -c 1 -w 1 "$1" >/dev/null; then
	    echo "no ping response from $1" 1>&2
	    exit 1
	fi
	NN=$1
    else
	NN=`ifconfig ${1:-usb0} |
	  sed '/.*inet addr:\([^ ]*\).*/{s//\1/;s/100$/101/;s/200$/202/;p;};d'`
    fi
fi
if [ "$NN" ]; then
    echo "SCP to $NN" 1>&2
    scp uImage $NN:
    ssh $NN 'PATH=$PATH:/usr/sbin;
      flash_eraseall /dev/mtd1 && nandwrite -p /dev/mtd1 uImage &&
      rm -f uImage && sync && sleep 1 && sync && sleep 1 && /sbin/reboot -f'
else
    echo "usbboot with idbg" 1>&2
    idbg-nnboot usb
    idbg-reset
    sleep 3
    usbboot -c "boot;nprog 1024 uImage 0 0 -n"
    idbg-nnboot nand
    idbg-reset
fi
