#!/usr/bin/lua

local random = math.random
local json = require "json"
math.randomseed(os.time())

local function uuid()
    local template ='xxxx-xxxx'
    return string.gsub(template, '[x]', function (c)
	local v = random(0, 0xf)	
	return string.format('%x', v)
    end)
end

function process_MSG(mid, topic, payload)
  print(topic, payload)
  pcall(function(topic,payload)
    payload = json.decode(payload)
    local time = os.date(payload['Time'])
    for sensor_type,sensor_data in pairs(payload) do
      if sensor_type ~= "Time" and sensor_type ~= "TempUnit" then
        for param,value in pairs(sensor_data) do
          conn:execute(string.format("CALL meteo.submit_mqtt('%s','%s','%s','%s',NULL)", topic,sensor_type,param,value))
          conn:commit()
          print(topic,sensor_type,param,value)
        end
      end
    end
  end, topic, payload) 
end

uci = require "uci"

config_name = arg[1]
if not config_name then
  config_name = "weathermon_mqtt"
end

mqtt_host = uci.get(config_name,"mqtt","server")
if not mqtt_host then
  mqtt_host="127.0.0.1"
end

mqtt_port = uci.get(config_name,"mqtt","port")
if not mqtt_port then
  mqtt_host=1883
end

mqtt_user = uci.get(config_name,"mqtt","username")
mqtt_pwd = uci.get(config_name,"mqtt","password")

mqtt_id = "wm-mqtt-"..uuid()

db_server = uci.get(config_name,"db","server")
db_name = uci.get(config_name,"db","db")
db_user = uci.get(config_name,"db","username")
db_pwd = uci.get(config_name,"db","password")

env = require("luasql.mysql").mysql()
conn = env:connect(db_name,db_user,db_pwd,db_server)
conn:execute("SET NAMES utf8")

MQTT = require "mosquitto"
mqtt_client = MQTT.new(mqtt_id)
if mqtt_user then
  mqtt_client:login_set(mqtt_user, mqtt_pwd)
end

mqtt_client:connect("estia.rvb-home.lan",1883)
mqtt_client.ON_MESSAGE = process_MSG

cur = conn:execute("SELECT DISTINCT topic FROM mqtt_topics WHERE topic<>''")
rec = cur:fetch()
while rec do
  mqtt_client:subscribe(rec)
  rec = cur:fetch()
end
 
mqtt_client:loop_forever()