ngx.req.read_body()
local json = loadfile(string.format("%s/bytecode/jsonlib", ngx.var.document_root))()
local arg = ngx.req.get_post_args()
local aliasfmt = string.format("%s/aliases/", ngx.var.document_root)
local allowwrite = true
local function err(reason, status)
    if status == nil then status = 404 end
    ngx.status = status
    ngx.say(reason)
    allowwrite = false
    ngx.eof()
end

for a, b in pairs(arg) do
    if a == "url" then
        url = b
    end if a == "alias" then
        alias = b
    end if a == "expires" then
        expires = b
    end
end

if ngx.var.uri == "/" then
    ngx.header.content_type = "text/html"; local htm = io.open(string.format("%s/etc/url.htm", ngx.var.document_root)):read("*a")
    ngx.say(htm); ngx.eof()
end

if ngx.var.uri == "/create" then
    if alias == "create" or alias == "etc" then ngx.say("This alias is not allowed.") ngx.eof() end
    if url:find("://") == nil then url = string.format("https://%s", url) end

    if expires == "" then
        url = json.encode({ url = url, expires = "nil" })
    else
        url = json.encode({ url = url, expires = expires })
    end

    local dateuri = json.decode(url)["expires"]
    if expires ~= "" then
        if dateuri:len() < 10 or dateuri:len() > 10 then
            err("Bad Data fmt.", 400)
        end
        if (expires:gsub("-", ""):gsub(":", "")) < os.date("%Y%m%d%T") then
            err("The Date less than on Server.", 400)
        end
    end

    if (url:find("%.")) == nil then
        err("Got invalid URL.", 400)
    end
    alias = alias:gsub("%p", {["/"] = "", ["."] = ""})

    local msg = string.format("Alias for \"%s\" is \"%s\".", json.decode(url)["url"], alias)
    if dateuri:len() ~= nil then
        msg = string.format("%s It expires at %s.", msg, dateuri)
    end

    aliasfmt = string.format("%s%s.json", aliasfmt, alias)

    if io.open(aliasfmt) ~= nil then
        err("Alias already exists.", 403)
    end

    if allowwrite ~= false then
        local file = io.open(aliasfmt, "w")
        file:write(url)
        file:close()

        ngx.say(msg)
        ngx.eof()
    end
else
    local jfile = ""
    local opnalias = string.format("%s%s.json", aliasfmt, ngx.var.uri)
    if io.open(opnalias) == nil then
        err("The Alias was not found.")
    else
        ngx.header["Cache-Control"] = {'no-cache'}
        jfile = io.open(opnalias, "r"):read("*all")
        date = (json.decode(jfile)["expires"]:gsub("-", ""))
        if date < os.date("%Y%m%d%T") then
            os.remove(opnalias)
        end
        ngx.redirect(json.decode(jfile)["url"], 301)
    end
end