#!/usr/bin/env python

# simple program to compile and upload Arduino code using the Arduino command line

import os
import subprocess
import sys

actionLine = sys.argv[1]
projectFile = sys.argv[2]

codeFile = open(projectFile, 'r')
startLine = codeFile.readline()[3:].strip()
#arduinoProg = codeFile.readline()[3:].strip()
boardLine = codeFile.readline()[3:].strip()
#portLine = codeFile.readline()[3:].strip()
endLine = codeFile.readline()[3:].strip()
codeFile.close()

if os.name == "nt":
	arduinoProg="A:\\arduino.exe"
	portLine="COM3"
else:
	arduinoprog="/usr/share/arduino/arduino" # incl. executable file
	portline="/dev/ttyusb0"

# print projectFile
# print startLine
# print actionLine
# print boardLine
# print portLine
# print endLine

if (startLine != "###########  start  ###########" or endLine != "###########   end   ###########"):
 print("\n Error in build-commands - can't process file")
 sys.exit()

arduinoCommand = arduinoProg + " --" + actionLine + " --board " + boardLine + " --port " + portLine + " --verbose " + projectFile

print("\n\n -- Arduino Command --")
print(arduinoCommand)

print("-- Starting %s --\n" %(actionLine))

presult = subprocess.call(arduinoCommand, shell=False)

if presult != 0:
 print("\n Failed - result code = %s --" %(presult))
else:
 print("\n-- Success --")

