require "apache2"
local redis = require "redis"
local regex = require "rex_pcre"
local mime = require "mime"
local cipher = require "openssl.cipher"


-- --------------------------------------------------------------------------
-- try to connect to redis
-- 
local redis_conn = nil


function _decrypt(message_and_iv, key)
  if message_and_iv:len() < 32 then
    -- io.stderr:write("message too short!\n")
    return ""
  end

  iv, _ = message_and_iv:sub(1, 16)
  message, _ = message_and_iv:sub(17, -1)

  local c = cipher.new("aes-256-cbc")

  c:decrypt(key, iv)
  cleartext, err = c:final(message)
  if err ~= nil then
    -- io.stderr:write(err .. "\n")
    return ""
  end

  -- io.stderr:write(cleartext .. "\n")
  return cleartext
end

function scw(r)
  local start_time = r:clock()
  local has_redis = false
  local ignore = os.getenv("SCW_IGNORE")

  -- io.stderr:write("url: " .. r.uri .. "\n")
  -- io.stderr:write(string.format("now: %d\n", r:clock()/1000/1000))

  if ignore ~= nil and regex.match(r.uri, ignore) then
    -- io.stderr:write(string.format("ignoring %s\n", r.uri))
    return apache2.DECLINED
  end

  -- --------------------------------------------------------------------------
  -- Does the user have an encrypted scw cookie that proves he is human?
  --
  local cookie_name = os.getenv("SCW_COOKIE")
  local cookie_key = r:base64_decode(os.getenv("SCW_KEY"))
  local human_cookie = r:getcookie(cookie_name)
  if human_cookie then
    human_cookie = r:base64_decode(r:unescape(human_cookie))
  end
  -- io.stderr:write("cookie: " .. r:base64_encode(human_cookie) .. "\n")
  local is_human = false

  if human_cookie ~= nil and cookie_key:len() == 32 then
    local cookie_data = _decrypt(human_cookie, cookie_key)
    -- io.stderr:write("cookie: " .. cookie_data.."\n")

    is_human = string.gsub(cookie_data, "scw|(.-)|(%d+)$", function (ip, exp)
      -- io.stderr:write(string.format("ip: %s, exp: %s\n", ip, exp))
      if ip == r.useragent_ip and r:clock() <= tonumber(exp) then
        return true
      end
      return false
    end)

    if is_human then
      -- io.stderr:write(string.format("c: %.3f ms\n", (r:clock() - start_time) / 1000.0))
      -- io.stderr:write(string.format("found scw cookie for %s\n", r.useragent_ip))
      return apache2.DECLINED
    end
  end

  -- --------------------------------------------------------------------------
  -- check for blacklist status
  --
  if pcall(function() redis_conn:ping() end) then
    has_redis = true
  else
    io.stderr:write("reconnecting to redis\n")
    local redis_host = os.getenv("SCW_REDIS_HOST")
    local redis_port = os.getenv("SCW_REDIS_PORT")
    io.stderr:write(string.format("redis host: %s\n", redis_host))
    if pcall(function() redis_conn = redis.connect(redis_host, 6379) end) then
      has_redis = true
    end
  end

  if has_redis then
    -- io.stderr:write(string.format("ip: %s\n", r.useragent_ip))
    local v = redis_conn:get("bl:" .. r.useragent_ip)
    -- local h = redis_conn:get("h:" .. r.useragent_ip)
    -- io.stderr:write(string.format("bl: %s, h: %s\n", tostring(v), tostring(h)))
    if v ~= nil then -- and h == nil then
      local rprotocol = "http"
      if r.is_https then
        rprotocol = "https"
      end

      local rport = ""
      if (r.is_https and r.port ~= 443) or (r.is_https ~= true and r.port ~= 80) then
        rport = string.format(":%d", r.port)
      end

      local referer = string.format("%s://%s%s%s", rprotocol, r.hostname, rport, r.unparsed_uri)
      r.headers_out["location"] = string.format("http://docker.scw.systems:8003/?src=%s&r=%s", r.useragent_ip, r:escape(referer))
--[[
      r.headers_in["X-SCW-IP"] = v
      r.handler = "proxy-server"
      r.proxyreq = apache2.PROXYREQ_REVERSE
      r.filename = string.format("proxy:http://captcha:8080/?src=%s&r=%s", r.useragent_ip, r.unparsed_uri)
--]]
      -- io.stderr:write(string.format("+ %.3f ms\n", (r:clock() - start_time) / 1000.0))
      return apache2.HTTP_MOVED_TEMPORARILY
    end
  end

  -- io.stderr:write(string.format("* %.3f ms\n", (r:clock() - start_time) / 1000.0))
  return apache2.DECLINED
end