local ngx_ssl = require('ngx.ssl')
local openssl = require('openssl')
local lfs = require('lfs')

local domains_ips = ngx.shared.domains_ips

local ssl_cache_file = '/var/cache/imunify360-webshield/ssl.cache'

local notfound_ssl = ngx.shared.notfound_ssl_domains

local function split(line, sep, num)

    local fields = {}
    local pos = 0
    local count = 0
    local strlen = line:len()

    while strlen > pos do
        local start, stop = line:find(sep, pos)

        if start == nil then
            table.insert(fields, line:sub(pos))
            break
        end

        table.insert(fields, line:sub(pos, start - 1))

        pos = stop + 1
        count = count + 1

        if count == num then
            table.insert(fields, line:sub(pos))
            break
        end
    end

    return fields
end


local function read_certs(_cache)

    local f = io.open(ssl_cache_file)

    if not f then
        return
    end

    local _names = setmetatable({}, {_mode="kv"})
    for key, _ in pairs(_cache) do
        _names[key] = true
    end

    for line in f:lines() do

        local _pair = split(line, ';;', 1)

        if #_pair ~= 2 then
            goto continue
        end

        _pair[2] = _pair[2]:gsub('\\r\\n', '\\n')     -- unifying EOL markers
        local data = _pair[2]:gsub('\\n', '\n')       -- cert itself

        local bundle = table.concat({data}, "\n")

        local xcrt = openssl.x509.read(bundle)

        if not xcrt then
            ngx.log(ngx.WARN, "Failed to get SSL XCRT (host: ", _pair[1], ")")
            goto continue
        end

        local crt = ngx_ssl.parse_pem_cert(bundle)

        if not crt then
            ngx.log(ngx.WARN, "Failed to get SSL CRT (host: ", _pair[1], ")")
            goto continue
        end

        local key = ngx_ssl.parse_pem_priv_key(bundle)

        if not key then
            ngx.log(ngx.WARN, "Failed to get SSL KEY (host: ", _pair[1], ")")
            goto continue
        end

        local val = {["xcrt"] = xcrt, ["crt"] = crt, ["key"] = key}
        _cache[_pair[1]] = val
        _names[_pair[1]] = nil
        ::continue::
    end

    for key, _ in pairs(_names) do
        _cache[key] = nil
    end

    f:close()
end


local function cache_getter()

    local _cache = {}
    local _cached_mtime = 0

    return function (name, addr)

        local mtime = lfs.attributes(ssl_cache_file, 'modification')

        if _cached_mtime ~= mtime then

            _cached_mtime = mtime

            read_certs(_cache)
            notfound_ssl:flush_all()        -- clear not_found dict
        end

        local dedicated_domain = domains_ips:get(addr)

        if not name then    -- No SNI found

            ngx.log(ngx.WARN, "Could not get SNI for request (IP: ", addr, ")")

            if dedicated_domain then
                name = dedicated_domain
            end
        end

        if name then

            local cert = _cache[name]
            if cert then
                return cert
            end

            local notfound_name = notfound_ssl:get(name)    -- we didn't find cert for the name earlier
            if notfound_name then                           -- so there's no need to look for it again
                return
            end

            for key, cert in pairs(_cache) do
               if cert["xcrt"]:check_host(name) then
                  return cert
               end
            end

            ngx.log(ngx.WARN, "Certificate not found (host: ", name, ")")

            ok, err, forced = notfound_ssl:set(name, true, 3600) -- cache name for missing cert for an hour
            if not ok then
                ngx.log(ngx.ERR, "Could not cache name (", name, ") of missing cert: ", err)
            end
        end
    end
end


local get_cert_by_host = cache_getter()


return {
    get_cert_by_host = get_cert_by_host
}
