package.path = package.path .. ';./controller-host/?/init.lua;./controller-host/?.lua'
local mqtt = require("mqtt")
local client

local file = ...
local fh = io.open(file, "rb")
local contents = fh:read("a")
fh:close()

function printTable(table, indentation)
	indentation = indentation or ""
	for name, value in pairs(table) do
		print(indentation .. tostring(name) .. ": " .. tostring(value))
	end
end

local function onMessage(data)
	print(data.payload)
end

local function onConnect(connack)
	if connack.rc ~= 0 then
		print("Connection to broker failed:", connack:reason_string())
		os.exit(1)
	end
	print("Connected to MQTT")

	assert(client:subscribe{
		topic = "spider/controller/stdout"
	})
	
	io.write("Sending payload...")
	assert(client:publish {
		topic = "spider/controller/payload",
		payload = contents,
		qos = 0
	})
	print(" DONE!")
end

client = mqtt.client {
	uri = "mqtt.seeseepuff.be",
	username = "mqtt_controller",
	clean = true,
	reconnect = 5,
}

client:on {
	connect = onConnect,
	message = onMessage,
}

print("Connecting")
mqtt.run_ioloop(client)
