local cookie = require('resty.cookie')
local digest = require('openssl').digest
local http = require "resty.http"
local json = require "cjson"
local pbi =   require "ws_message_pb"

local i360_socket = "unix:/var/run/defence360agent/protobuf.sock"


local function captchacheck_make_captcha_cookie_expire()
    local cookie_obj, err = cookie:new()
    if not cookie_obj then
        ngx.log(ngx.ERR, "Failed to init cookie: ", err)
        return
    end

    local current_timestamp = os.time()
    local expiration_date = os.date(
        "!%a, %d-%b-%y %H:%M:%S GMT", current_timestamp - 86400)  -- Let it expire

    local ok, err = cookie_obj:set({
        key = "cl-bypass-cache",
        value = "no",
        domain = ngx.var.host,
        samesite = "Lax",
        httponly = true,
        path = "/",
        expires = expiration_date
    })
    if not ok then
        ngx.log(ngx.ERR, "Could not set cookie: ", err)
    end
end


local function captchacheck_send_OK ()
    ngx.status = ngx.HTTP_OK
    ngx.header.content_type = "application/json; charset=utf-8"
    ngx.say(json.encode({ success = true }))
    return ngx.exit(ngx.HTTP_OK)
end


local function captchacheck_send_ERR ()
    ngx.status = ngx.HTTP_BAD_REQUEST
    return ngx.exit(ngx.HTTP_BAD_REQUEST)
end


local function captchacheck_get_value(key_name)
    ngx.req.read_body()
    local value
    local args = ngx.req.get_post_args()
    if args then
        for key, val in pairs(args) do
            if key == key_name then
                value = val
                break
            end
        end
    end
    return value
end


local function captchacheck_write_format(little_endian, format, ...)
  local res = ''
  local values = {...}
  for i=1,#format do
    local size = tonumber(format:sub(i,i))
    local value = values[i]
    local str = ""
    for j=1,size do
      str = str .. string.char(value % 256)
      value = math.floor(value / 256)
    end
    if not little_endian then
      str = string.reverse(str)
    end
    res = res .. str
  end
  return res
end


local function captchacheck_composeMessage(uid, ip, success)
    local msg = pbi.SendInfo()
    msg.ip = ip
    msg.method = msg.WEBSHIELD
    msg.timestamp = os.time(os.date("!*t"))

    if uid then   -- yes, UID might be absent
        msg.websh.user_id = uid
    end

    if success then
        msg.websh.captcha = msg.websh.PASSED
    else
        msg.websh.captcha = msg.websh.FAILED
    end

    local serialized = msg:SerializeToString()
    return captchacheck_write_format(false, "2", string.len(serialized)) .. serialized
end


local function captchacheck_notify_peer (uid, ip, success)

    local sock = ngx.socket.tcp()
    sock:settimeout(1000)
    local ok, err = sock:connect(i360_socket)

    if not ok then
        ngx.log(ngx.ERR, "Could not connect to i360 socket: ", err)
        return
    end

    local sent, err = sock:send(captchacheck_composeMessage(uid, ip, success))

    if not sent then
        ngx.log(ngx.ERR, "Could not send to i360 socket: ", err)
    end

    sock:close()
end


local function captchacheck_google_query (data, remote_address)

    local conn = http.new()
    local google_url = "https://www.google.com/recaptcha/api/siteverify"
    local default_secret_key = "6LfwghwUAAAAALdx_xobqogq6hpa4pR8usRovQl8"
    local custom_secret_key = ngx.var.wscaptcha_secret_key
    local captcha_secret_key = custom_secret_key or default_secret_key
    local body = string.format(
        "secret=%s&response=%s&remoteip=%s",
        captcha_secret_key, data, remote_address)

    local res, err = conn:request_uri(google_url, {
        method = "POST",
        body = body,
        headers = {
          ["Content-Type"] = "application/x-www-form-urlencoded",
        }
    })

    if not res then
        ngx.log(ngx.ERR, "Could not query google: ", err)
        return
    end

    local decoded = json.decode(res.body)

    if not decoded.success then
        ngx.log(ngx.ERR, "Captcha site verification error: [", table.concat(decoded["error-codes"], ", "), "]")
    end

    return decoded.success
end


local function set_untrusted_uid_cookie()
    local cookie_obj, err = cookie:new()
    if not cookie_obj then
        ngx.log(ngx.ERR, "Failed to init cookie: ", err)
        return
    end

    local cookie_name = ngx.var.ws_cookie_name
    local user_agent = ngx.var.http_user_agent
    if user_agent == nil then
        user_agent = ''
    end
    local user_data = ngx.var.wsuserip .. user_agent
    local secret_key = ngx.var.ws_untrusted_secret_key
    local ttl = tostring(ngx.time() + ngx.var.ws_cookie_ttl)
    local hashsum = digest.digest('sha1', user_data .. secret_key .. ttl, false)
    local val = hashsum .. "." .. ttl .. ".0"

    local current_timestamp = os.time()
    local offset = 30 * 24 * 3600     -- 30 days
    local expiration_date = os.date(
        "!%a, %d-%b-%y %H:%M:%S GMT", current_timestamp + offset)

    local ok, err = cookie_obj:set({
        key = cookie_name,
        value = val,
        domain = ngx.var.host,
        samesite = "Lax",
        httponly = true,
        path = "/",
        expires = expiration_date
    })
    if not ok then
        ngx.log(ngx.ERR, "Could not set cookie: ", err)
    end
end


local function to_static()
    local uri, search_pattern = ngx.var.uri, "/a9bc224bd710f56d27affffddc764239b58c3faa0"
    local start_pos, end_pos = string.find(uri, search_pattern)
    if start_pos == 1 then
        return true
    end
    return false
end


local function request_is_text()
    if ngx.var.http_accept == nil then
        return false
    end
    if string.find(ngx.var.http_accept, "text/html") or ngx.var.http_accept == "*/*" then
        return true
    end
    return false
end


local function process_request()

    if to_static() then
        return ngx.exec("@to_static")
    end

    local ip_status = ngx.var.webshield_ip_status

    -- Whitelist ezoic traffic if a user wants to
    local trust_ezoic = ngx.var.trust_ezoic
    local ua_header = ngx.var.http_user_agent
    if trust_ezoic == "1" and ua_header ~= nil and ua_header:find('[Xx]%-[Mm]iddleton') then
        return ngx.exec("@to_backend")
    end

    -- Traffic from whitelisted sources is passed as is without checks
    if ip_status == "WHITE" then
        return ngx.exec("@to_backend")
    end

    -- Traffic from local blacklisted sources is denied
    if ip_status == "BLACK_LOCAL" then
        return ngx.exit(403)
    end

    if ip_status == "COUNTRY_BLACK" then
        return ngx.exit(403)
    end

    -- Traffic from static whitelisted sources is passed as is without checks
    if ip_status == "WHITE_STATIC" then
        return ngx.exec("@to_backend")
    end

    -- Traffic from blacklisted sources is denied
    if ip_status == "BLACK" then
        return ngx.exit(403)
    end

    local dest_domain_whitelisted = ngx.var.domain_whitelisted
    local wscheck = ngx.var.wscheck

    local wsuserid = ngx.var.wsuserid

    local userip = ngx.var.wsuserip                   -- client IP address
    local destination_port = ngx.var.destination_port -- initial destination port

    local splashscreen_antibot = ngx.var.splashscreen_antibot

    if dest_domain_whitelisted == "1" then          -- If a user goes to a whitelisted domain
        if not wsuserid and splashscreen_antibot == "1" then
            set_untrusted_uid_cookie()              -- client checks enabled but no UID found
        end                                         -- set untrusted cookie (because we did not check its UA)

        return ngx.exec("@to_backend")              -- let him proceed
    end

    if ip_status == "GRAY" then                     -- User is graylisted

        local remote_proxy       = ngx.var.remote_proxy
        local cloudflare_captcha = ngx.var.cloudflare_captcha

        -- pass cloudflare traffic to backend without attempts to show captcha
        if remote_proxy == "cloudflare" and cloudflare_captcha  == "0" then
            return ngx.exec("@to_backend")
        end

        if not wsuserid then
            ngx.var.wscaptcha = "1"                 -- indicate that splashscreen_as_captcha shown
            if request_is_text() then               -- if text/html
                return ngx.exec("@to_splashscreen") -- show splashscreen to him
            end
            ngx.status = 415                        -- otherwise return
            ngx.say("")                             -- custom error code
            return ngx.exit(415)
        end

        return ngx.exec("@to_backend")              -- let him proceed
    end

    if splashscreen_antibot == "1" and not wsuserid and (destination_port == "2083" or destination_port == "2082") and ngx.var.cpanel_protection == "1" and ip_status ~= "WHITE" then
        return ngx.exec("@to_splashscreen")         -- Show splashscreen
    end

    if splashscreen_antibot == "1" and not wsuserid and ip_status == "SPLASH" then
        return ngx.exec("@to_splashscreen")         -- Show splashscreen
    end

    return ngx.exec("@to_backend")                  -- let him proceed
end

-- currently files reqrouter.lua and captchacheck.lua has been united
-- because it's simpler to enable/disable functionality this way
-- prefix 'captchacheck_' has been prepended to all routines added from
-- captchacheck
local function captchacheck ()

    local ip_status = ngx.var.webshield_ip_status

    -- Traffic from static whitelisted sources is passed as is without checks
    if ip_status == "WHITE_STATIC" then
        return ngx.exec("@to_backend")
    end

    local value = captchacheck_get_value("captcha_value") -- get POST-passed value

    if not value then
        return captchacheck_send_ERR()
    end

    local userid   = ngx.var.wsuserid
    local remote_address = ngx.var.wsuserip

    local response = captchacheck_google_query(value, remote_address)

    if response == nil then
        return captchacheck_send_ERR()
    end

    captchacheck_notify_peer(userid, remote_address, response)

    captchacheck_make_captcha_cookie_expire()

    if response then
        return captchacheck_send_OK()
    end

    return captchacheck_send_ERR()
end

if ngx.var.access_check_enabled == "0" then
  if ngx.var.uri == "/captchacheck" then
      return captchacheck()
  end

  if ngx.var.uri == "/z0f76a1d14fd21a8fb5fd0d03e0fdc3d3cedae52f" then
      return ngx.exec("@to_wsidchk")
  end

  return process_request()
else
  return ngx.exec("@by_default")
end
