#!/usr/bin/lua
json = require("cjson")
fbwifi = require("fbwifi")

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

response = { api_version = "2.0", token = json.null }
client_mac = ""

function process_cors()
        origin = os.getenv("HTTP_ORIGIN")
        if string.len(origin or '') > 0 then
                allow_list = state:get("fbwifi", "main", "cross_origin_allow_rules")
                for _, value in pairs(allow_list) do
                        if value == origin then
                                print("Access-Control-Allow-Origin: "..origin)
                                print("Vary: Origin")
                                break
                        end
                end
        end
end

function map_remote_mac_to_token(client)

	for key, value in pairs(client) do
		if
			key == 'mac' and
			value == client_mac
		then
			response.token = client.token
			return false -- escape outer loop
		end
	end
end

function getClientToken(client_ip)
	f = io.popen("awk '/"..client_ip..".*0x2/ { printf(\"%s\", $4) }' /proc/net/arp", 'r')
	client_mac = assert(f:read('*a'))
	f:close()

	state:foreach("fbwifi", "client", map_remote_mac_to_token)
end

function getGatewayId()
	id = string.match(GATEWAY_TOKEN, 'FBWIFI:GATEWAY|[0-9]*|([0-9]*)')
	return id
end

process_cors()
print("Content-type: application/json; charset=utf-8\n")

getClientToken(os.getenv("REMOTE_ADDR"))
response.gateway_id = getGatewayId()

print( json.encode(response) )
