#!/usr/bin/lua

http = require("ssl.https")
json = require("cjson")
log = require("posix.syslog")
socket = require("socket")
require("uci")
fbwifi = require("fbwifi")

GATEWAY_TOKEN = fbwifi.gateway_token()
state = uci.cursor("/var/state", "/tmp/fbwifi")

payload="name="..socket.dns.gethostname()

function queue_ssid_update(iface)
	bssid_file="/sys/class/net/br-"..iface["network"].."/address"
	local file = io.open(bssid_file)
        if file then
            for line in file:lines() do
		payload=payload.."&bssid[]="..line
            end
	    file:close()
	    payload=payload.."ssid[]="..iface["ssid"]
        else
	    log.syslog(log.LOG_WARNING, "[fbwifi] Failed to find BSSID for interface br-"..iface["network"])
        end
end

state:foreach("wireless", "wifi-iface", queue_ssid_update)

URL="https://api.fbwifi.com/v2.0/gateway"
body, code, headers = http.request(URL.."?access_token="..GATEWAY_TOKEN, payload)
if code == 200 then 
	log.syslog(log.LOG_INFO, "[fbwifi] gateway information updated "..body)
	os.exit(0)
else
	log.syslog(log.LOG_WARNING, "[fbwifi] gateway API failed "..body)
	os.exit(code)
end
