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

state = uci.cursor("/var/state", "/tmp/fbwifi")
client_mac = ""
token = ""

response = {}
response['venue-info-url'] = state:get("fbwifi", "main", "capport_venue_info_url")

function map_remote_mac_to_token(client)
        for key, value in pairs(client) do
                if
                        key == 'mac' and
                        value == client_mac
                then
			token = client.token
                        return false
                end
        end
end

function hasValidToken(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)

	return 0 < string.len(token)
end

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

client = os.getenv("REMOTE_ADDR")
response['captive'] = not hasValidToken(client)

if response['captive'] then
	response['user-portal-url'] = state:get("fbwifi", "main", "captive_portal_url")
end

print( json.encode(response) )
