#!/bin/sh
#
# Flash stock nanostation for use in WL network
#
# Rick van der Zwet <info@rickvanderzwet.nl>
#
DIRNAME=`dirname $0`
TOTAL_TRIES=60

# Argument helpers
if [ -z "$2" ]; then
  echo "Usage: $0 <node> <iface>"
  exit 128
fi

if [ ! -r "fwupdate.bin" ]; then
  echo "Unable to read fwupdate.bin (download latest firmware file)"
  exit 1
fi

HOSTNAME=$1
NS_IFACE=$2


# Create configuration
$DIRNAME/gformat.py test $HOSTNAME $NS_IFACE-ns5m.conf > system.cfg.new
if [ $? -ne 0 ]; then
  echo "Unable to generate configuration file"
  exit 1
fi

# Verify connectivity
TRY=0
while true; do
  sshpass -p ubnt ssh -oUserKnownHostsFile=/dev/null ubnt@192.168.1.20 'uname -a'
  if [ $? -eq 0 ]; then
    break
  fi

  TRY=`expr $TRY + 1`
  echo "Unable to connect to NanoStation (attempt $TRY of $TOTAL_TRIES)"
  if [ $TRY -ge $TOTAL_TRIES ]; then
    exit 1
  fi
  sleep 1
done

# Variables needed from Nanostaion, as to be filled into configuration
MAC=`arp -na | awk '/192.168.1.20/ {print $4}'`
IFACE=`arp -na | awk '/192.168.1.20/ {print $7}'`

# XXX: Automatically put MAC into configuration
echo "# MAC of NanoStation is $MAC"

# Flash node
sshpass -p ubnt scp -oUserKnownHostsFile=/dev/null system.cfg.new fwupdate.bin ubnt@192.168.1.20:/tmp || exit 1
sshpass -p ubnt ssh -oUserKnownHostsFile=/dev/null ubnt@192.168.1.20 'cfgmtd -w -f /tmp/system.cfg.new && fwupdate -m' || exit 1

echo "Ones the leds are off configuration is done"

# TODO: Login on auto-alias IP address to verify
sudo tcpdump -nn -v -i $IFACE -s 1500 -c 1 'ether[18:4] == 0x000c2000'

echo "All done, press CTRL-C to quit"
while true; do
  echo -ne "\a"
  sleep 5
done
