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

# 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
ping -c 1 192.168.1.20
if [ $? -ne 0 ]; then
  echo "Unable to connect to NanoStation"
  exit 1
fi

# 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
sshpass -p ubnt ssh -oUserKnownHostsFile=/dev/null ubnt@192.168.1.20 'cfgmtd -w -f /tmp/system.cfg.new && fwupdate -m'

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 -e "\a"
  sleep 1
done
