import re
import sys
import subprocess
import MySQLdb as mdb

x=open("Files/data.txt", "r")
line="something"

def upload():
	line=x.readline()
	tmp = re.split(';',line)
	name=tmp[1]
	address=tmp[2]
	port=tmp[3]
	fw_file="Files/" + tmp[4].rstrip('\r\n')

	myargs= (" -i %s -a %s -p %s") % (fw_file,address,port) 
	subprocess.call("python tcp_fw.py" + myargs, shell=True)

while line[0] =="X":
	upload()
	try:
		dbcon = mdb.connect('localhost', 'server', 'server123', 'WSN')
		cur = dbcon.cursor()
		line = "SELECT 1 FROM nodes WHERE node_name='%s'" % (name)
		query = cur.execute(line)
		if query == 1:    
			line = "INSERT INTO nodes(IP,port,fw_version) VALUES('%s','%s','%s','%s') WHERE node_name='%s'" % (address,port,fw_file,name)
		else:
			line = "INSERT INTO nodes(node_name,IP,port,fw_version) VALUES('%s','%s','%s','%s')" % (name,address,port,fw_file)
		cur.execute(line)    
		dbcon.commit()
		print "%s added to Database" % name
	except mdb.Error, e:
  
		print "Error %d: %s" % (e.args[0], e.args[1])
		sys.exit(1)

	finally:
    
		if dbcon:
			dbcon.close()


