#!/usr/bin/lua
require("uci")
log = require("posix.syslog")
fbwifi = require("fbwifi")

state = uci.cursor("/var/state", "/tmp/fbwifi")
function process_cors()
	origin = os.getenv("HTTP_ORIGIN")
	log.syslog(log.LOG_INFO, string.format("[fbwifi] [auth] process_cors origin %s", origin or 'not found') )
	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
				log.syslog(log.LOG_INFO, "[fbwifi] [auth] process_cors Appending CORS Headers to HTTP")
				print("Access-Control-Allow-Origin: "..origin)
				print("Vary: Origin")
				break
			end
		end
	else	
		log.syslog(log.LOG_INFO, "[fbwifi] [auth] process_cors No CORS Headers added to Response")
	end
end

method = os.getenv("REQUEST_METHOD")
if method == 'GET' then
	log.syslog(log.LOG_INFO, "[fbwifi] [auth] GET handler")
	print("Status: 302 Found")
	print("Location: "..state:get("fbwifi", "main", "landing_page_url"))
	process_cors()
	print ('\n')

elseif method == 'POST' then
	local token
	
	log.syslog(log.LOG_INFO, "[fbwifi] [auth] POST handler")
	process_cors()
	print("Status: 200 OK")

	form_data=io.read()
	while form_data do
		token = string.match(form_data, '[%d]+')
		if string.len(token or '') > 14 then

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

			if fbwifi.validate_token(token) then
                                log.syslog(log.LOG_INFO, string.format( "[fbwifi] [auth] POST handler : Validating Token (%s) for MAC (%s)", token or 'nil', client_mac or 'nil') )
				fbwifi.instate_client_rule(token, client_mac)
				print("\n{\"valid\":true}\n")
			else
                                log.syslog(log.LOG_WARNING, string.format( "[fbwifi] [auth] POST handler : ! Invalid token (%s) for mac (%s) !", token or 'nil', client_mac or 'nil') )
				fbwifi.revoke_client_rule(token)
				print("\n{\"valid\":false}\n")
			end
			log.syslog(log.LOG_INFO, "[fbwifi] [auth] POST handler completed")
			return
		end

		form_data=io.read()
	end
	print ('\n')

	log.syslog(log.LOG_WARNING, string.format("[fbwifi] [auth] POST handler : token not found" ))
	fbwifi.revoke_client_rule(token)
	print("\n{\"valid\":false}\n")
end
