local template = require 'resty.template'
local digest = require('openssl').digest
local splashscreen_sessions = ngx.shared.splashscreen_sessions


local function make_temp_uid()
    local user_agent = ngx.var.http_user_agent or 'missing_agent'
    local user_data = ngx.var.remote_addr .. user_agent .. tostring(ngx.now())
    local hashsum = digest.digest('sha1', user_data, false)
    return hashsum
end


local function generate(seq)

    local function split(data)
        local buffer = {}
        for i in data:gmatch("%w") do
            table.insert(buffer, tonumber(i))
        end
        return buffer
    end

    local digits = split(seq)
    local ready = {}

    for i, v in ipairs(digits) do
        local buffer = {"("}
        local item = "+!![]"
        if v == 0 then
            table.insert(buffer, "+![]")
        elseif v == 1 then
            table.insert(buffer, "+!+[]")
        else
            table.insert(buffer, "+!+[]")
            for i = 1, v - 1 do
                table.insert(buffer, item)
            end
        end
        if i % 2 == 0 then
            table.insert(buffer, "+[]")
        end
        table.insert(buffer, ")")
        table.insert(ready, table.concat(buffer, ""))
    end

    return "+(" .. table.concat(ready, "+") .. ")"
end

local function prepare_data()
    local uri = ngx.var.request_uri
    local uri_parts = {ngx.var.scheme, '://', ngx.var.host}
    local destination_port = ngx.var.destination_port
    if destination_port ~= '80' and destination_port ~= '443' then
        table.insert(uri_parts, ':' .. destination_port)
    end
    if uri ~= '' and uri ~= '/' then
        table.insert(uri_parts, uri)
    end

    local userid = make_temp_uid()                  -- generate temporary UID (SHA1 hashsum)
    local _start = tonumber(userid:sub(0, 6), 16)   -- take first six symbols and last six ones and
    local _stop = tonumber(userid:sub(-6), 16)      -- convert them to decimal
    local _w = generate(tostring(_start))           -- generate 2 JS check sequences from the decimals
    local _e = generate(tostring(_stop))
    local sum = _start + _stop                      -- Find the sum of the decimals and convert it to hex
    local xsum = string.format("%X", sum)

    -- place original URI to shared dictionary with the hex sum as key
    splashscreen_sessions:set(xsum, table.concat(uri_parts), 60)

    return {
        westval=_w,
        eastval=_e
    }
end

local accept = ngx.var.http_accept
if accept ~= nil and string.find(string.lower(accept), "json") ~= nil then
    ngx.header["Content-Type"] = "application/json"
    ngx.say('{"message": "Access denied by Imunify360 bot-protection. IPs used for automation should be whitelisted"}')
elseif accept ~= nil and string.find(accept, "text/") == nil and accept ~= "*/*" then
    ngx.status = 415                        -- return custom error code
    ngx.say("")
else
    local vars = prepare_data()
    template.render('index.html', vars, 'splashscreen')
end
