local ngx_ssl = require('ngx.ssl')
local ssl_utils = require("webshield.sslutils")


local function get_address()

    local addr, atype, err = ngx_ssl.raw_server_addr()

    if not addr then
        ngx.log(ngx.ERR, "Unable to fetch raw server addr: ", err)
        return
    end

    local byte = string.byte

    if atype == "inet" then  -- IPv4

        local ip = string.format(
            "%d.%d.%d.%d",
            byte(addr, 1), byte(addr, 2), byte(addr, 3), byte(addr, 4))

        return ip
    elseif atype == "inet6" then -- IPv6

        local ip = string.format(
            "%02x%02x:%02x%02x:%02x%02x:%02x%02x:%02x%02x:%02x%02x:%02x%02x:%02x%02x",
            byte(addr, 1), byte(addr, 2), byte(addr, 3), byte(addr, 4),
            byte(addr, 5), byte(addr, 6), byte(addr, 7), byte(addr, 8),
            byte(addr, 9), byte(addr, 10), byte(addr, 11), byte(addr, 12),
            byte(addr, 13), byte(addr, 14), byte(addr, 15), byte(addr, 16))

        return ip
    else                         -- unix socket unsupported
        ngx.log(ngx.WARN, "IP addresses only supported")
    end
end


local function set_cert()

    local addr = get_address()
    if not addr then
        return
    end

    local name = ngx_ssl.server_name()

    local ssl = ssl_utils.get_cert_by_host(name, addr)

    if not ssl then
        return
    end

    ngx_ssl.clear_certs()

    ngx_ssl.set_cert(ssl.crt)

    ngx_ssl.set_priv_key(ssl.key)
end

set_cert()
