#!/usr/bin/lua

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

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

request = { 
	tokens = {}, 
	traffic_type = "total",
	config_version = state:get("fbwifi", "main", "config_version")
}

function queue_token(client)

	request.tokens[client.token]={
		incoming = json.null,
		outgoing = json.null,
		connected_time_sec = json.null,
		inactive_time_sec = json.null,
		signal_rssi_dbm = json.null,
		--expected_tpus_mbps = json.null,
		is_connected = true
	}

end

state:foreach("fbwifi", "client", queue_token)
print( "\nRequest:\n"..json.encode(request) )

URL="https://api.fbwifi.com/v2.0/tokens"
BODY=string.format(
	"tokens=%s&traffic_type=%s&config_version=%s",
	json.encode(request.tokens),
	"total",
	state:get("fbwifi", "main", "config_version")
)

body, code, headers = https.request(URL.."?access_token="..GATEWAY_TOKEN, BODY)

if code then
	print( "\nResponse:\n"..body )
end

response = json.decode(body)
--print(response)
--table.foreach(response,print)
--table.foreach(response.tokens,print)

if response.config_valid then
	log.syslog(log.LOG_INFO, "[fbwifi] Config validated")
else
	log.syslog(log.LOG_WARNING, "[fbwifi] config is stale, refreshing config")
        local result = os.execute("/usr/sbin/fbwifi reload")
        if result == 0 then
                log.syslog(log.LOG_INFO, "[fbwifi] successfully fetched and loaded new config ")
        else
                log.syslog(log.LOG_WARNING, "[fbwifi] failed to fetch and load new config, possible stale config")
        end
end

function process_token(token, metadata)
	table.foreach(metadata,print)
	if metadata.valid then
		print("OK: "..token)	
	else
		print("Nok: "..token)	
		fbwifi.revoke_client_rule( token )
	end
end
table.foreach(response.tokens,process_token)
