#!/bin/bash 

if [ $# -lt 1 ]; then
	echo "Usage: $0 <sketch name> [upload]"
	exit 0
fi 

# assign WIFI_SSID and WIFI_PASS in external file ../info
# source "../info"

SKETCH="$1/$1.ino"

TMP="/tmp/ESPcompile.tmp"

# MAKE_FILE="/home/dmitry/Bin/SDK/ESP/makeEspArduino.21.02.22/makeEspArduino.mk"
MAKE_FILE="/home/dmitry/Bin/SDK/ESP/makeEspArduino/makeEspArduino.mk"
# ESP_SDK_ROOT=/home/dmitry/Bin/SDK/ESP/esp8266				# keep it without quotation marks

# ESP_SDK_ROOT=~/Bin/SDK/ESP/Arduino
# ESP_SDK_ROOT=~/Bin/SDK/ESP/esp8266_3.1.2
# ESP_SDK_ROOT=~/Bin/SDK/ESP/esp8266_3.0.2
ESP_SDK_ROOT=~/Bin/SDK/ESP/esp8266_2.5.0


# LIBS=/home/dmitry/Bin/SDK/ESP/esp8266/libraries
# USER_SRC_PATTERN="version.h"

DATE=$(date +"%d.%m.%y")
echo "#define	VERSION			\"$DATE\"" > "$1/version.c"

# nodemcuv2, generic, esp8285
make -f "$MAKE_FILE" ESP_ROOT="$ESP_SDK_ROOT" F_CPU=160000000L CHIP=esp8266 BOARD=esp8285 SKETCH="$SKETCH" $2 2>&1 | tee "$TMP"

if [ -s "$TMP" ]; then 
	binSRC=$( cat "$TMP" | grep Linking | sed -e 's/Linking //g' )
	cp "$binSRC" .

	serialPort=$(cat "$TMP" | grep "opening port" | awk '{split($0,a," "); print a[3]}')
else
	serialPort=/dev/ttyUSB0
fi