#!/bin/sh
# on startup the system is not quite ready when called, so lets play it safe and wait a while
sleep 4
if [ -r /data/ftp/internal_000/scripts/pprz.conf ]; then
	source /data/ftp/internal_000/scripts/pprz.conf
	echo "Read config"
else
	echo "No config found, using default"
	START_TELNET=1
	START_ADB=1
	JOIN_WIFI=0
	START_PPRZ=0
fi
if [ "$JOIN_WIFI" -gt "0" ]
then
  echo "Scanning WiFi networks..."
  # see if wifi network with SSID swarmhub is available
  if (bcmwl escanresults | grep "$WIFI_SSID")
  then
        # disable wifi and bring back up again
        ifconfig eth0 down
        bcmwl down
        bcmwl band auto
        bcmwl autocountry 1
        bcmwl up
        ifconfig eth0 up
        # set AP mode to 0 (parrot default is 1 for ad-hoc host)
        bcmwl ap 0
        # join wifi network
        if [ "$WIFI_AMODE" == "none" ]; then
		echo "No Authentication"
        	wificmd="bcmwl join $WIFI_SSID"
       	else
       		echo "$WIFI_AMODE Authentication"
        	wificmd="bcmwl join $WIFI_SSID key $WIFI_KEY amode $WIFI_AMODE"
        fi
        eval $wificmd
        sleep 2
        # from the udhcpc message clip the leased IP address
        dhcpmsg=`udhcpc -n -b -i eth0 -s /data/ftp/internal_000/scripts/config_network.script -x hostname:$(hostname)`
        echo $dhcpmsg > /data/ftp/internal_000/scripts/MSG_latest_DHCP
        # check if previous command returned a valid IP address
        if (echo $dhcpmsg | egrep "[[:digit:]]{1,3}\.[[:digit:]]{1,3}\.[[:digit:]]{1,3}\.[[:digit:]]{1,3}" -o)
        then
                dhcpip=`echo $dhcpmsg | egrep "[[:digit:]]{1,3}\.[[:digit:]]{1,3}\.[[:digit:]]{1,3}\.[[:digit:]]{1,3}" -o | head -1`
                echo DHCP success, using IP $dhcpip
                BLDC_Test_Bench -n -M 2
        else
                echo DHCP failed, reverting back to default
		/sbin/broadcom_reset.sh
		BLDC_Test_Bench -n -M -2
	fi
  else
	# print wifi status
	echo "SSID $WIFI_SSID not found"
  fi
fi
ifconfig > /data/ftp/internal_000/scripts/MSG_latest_ifconfig

# Telnet & adb                                                      
echo "Starting telnet & adb" | ulogger -t "NetworkUSB" -p I         
if [ "$START_TELNET" -gt "0" ]
then
	/usr/sbin/telnetd -l /bin/login.sh
fi
if [ "$START_ADB" -gt "0" ]
then                                  
	/usr/bin/pstart adbd
fi
if [ "$START_PPRZ" -gt "0" ]                                  
then                                                         
	if [ -r /data/ftp/internal_000/paparazzi/ap.elf ]; then
		/data/ftp/internal_000/paparazzi/ap.elf  > /dev/null 2>&1 &
	fi
fi  
