local redirects_dir = ngx.var.shortener_data_dir or "/var/cache/url-shortener"
local redirect_status = ngx.var.shortener_redirects_status or 302
local sh_hostname = ngx.var.shortener_host or "default"
local hostdir = redirects_dir .. "/" .. sh_hostname

local function handle_request()
    local request_uri = ngx.var.request_uri
    local hash = request_uri:match("^/([^?]+)")
    local return_code = 302

    if hash then
        local normalized_hash = string.gsub(hash, "[^%w]", "-")
        local config_file = hostdir .. "/nginx/" .. normalized_hash
        local log_file = hostdir .. "/logs/" .. normalized_hash
        local urlfile = io.open(config_file, "r")

	    if urlfile then
	        local url = urlfile:read():match("# (.+)")
	        if url then
	            for line in urlfile:lines() do
                    if line:match("return%s+(%d+)%s+(.+)") then
                        redirect_status = tonumber(line:match("return%s+(%d+)"))
			            break
                    end
                end

                local remote_addr = ngx.var.remote_addr
                local time_local = ngx.var.time_local
                local request = ngx.var.request
                local status = ngx.var.status
                local body_bytes_sent = ngx.var.body_bytes_sent
                local http_referer = ngx.var.http_referer
                local http_user_agent = ngx.var.http_user_agent

                local log_entry = string.format("%s - %s [%s] \"%s\" %s %s \"%s\" \"%s\"",
                                                remote_addr, "-", time_local, request, status, body_bytes_sent,
                                                http_referer, http_user_agent)

                local file = io.open(log_file, "a")
		        if file then
		            os.execute("/bin/touch " .. hostdir .. "/update.d/" .. normalized_hash)
                    file:write(log_entry .. " - from lua\n")
                    file:close()
		        else
		            ngx.log(ngx.ERR, "Could not read " .. log_file)
                    ngx.exit(ngx.HTTP_NOT_FOUND)
	            end
	            ngx.redirect(string.gsub(url, "\n", ""), redirect_status)
	        else
                ngx.exit(ngx.HTTP_NOT_FOUND)
            end
	    else
            ngx.exit(ngx.HTTP_NOT_FOUND)
	    end
    else
        ngx.exit(ngx.HTTP_NOT_FOUND)
    end
end

handle_request()
