import process.popen;

namespace process.ruby;

class cgi{
	ctor(response,request,cgiPath,...){
		
		var env = request.environ;
		env.REDIRECT_STATUS = 200;
		env.PHP_SELF = env.PATH_INFO;
		if( ..string.endWith(env.PATH_INFO,".rb",true) ){
			env.SCRIPT_NAME =  env.PATH_INFO;
			env.SCRIPT_FILENAME = env.PATH_TRANSLATED;
		}
		env.PATH_INFO = null;
		
		var prcs,err = ..process.popen(cgiPath, {cgiPath;..io.fullpath(request.path)}, {environment = env });
		if(!prcs){
			response.error(err);
			return; 
		}
		
		prcs.writeClose();
		prcs.codepage = 65001;
		if(request.contentLength){
			prcs.write( request.postData() )
		} 
		
		var out = prcs.read(-1);
		var err = prcs.readErr(-1);
		prcs.close();
		
		if(#out) { 
			response.charset = "";
			if(#err){..io.stderr.write(err);}
			
			var strHeaders,body = ..string.match(out,'(.+?)\r+\n\r+\n(.*)'); 
			
			var httpHeaders = ..string.splitEx(strHeaders,"\r\n");
			var lastHeaderKey;
			for(i=#httpHeaders;1;-1){
				var line = httpHeaders[i];
				if(line[1]==' ' || line[1]=='\t'){
					if(lastHeaderKey){ httpHeaders[ lastHeaderKey ] = httpHeaders[ lastHeaderKey ] ++ ..string.trimleft(line); }
					continue;
				};
					
				var h = ..string.splitEx(line,"\:\s*",2); 
				if(#h == 2){
					var k = ..string.lower(h[1]);
					var v = h[2];

					if(k=="content-type"){
						response.contentType = v;
					}
					elseif(k=="status"){
						response.status = v;
					}
					else {
						response.headers[h[1]] = v;
					} 
				}  
			}
			
			response.write(body); 
		}
		elseif(#err){ 
			response.error(err) 
		}
	} 
}

/**intellisense()
process.ruby.cgi = 用于HTTP服务器创建Ruby CGI进程\n适用于 wsock.tcp.simpleHttpServer 或 wsock.tcp.asynHttpServer
process.ruby.cgi(.(response,request,cgiPath,->->->) = @response,@request参数为HTTP服务器的请求与响应对象,\n@cgiPath指定 ruby.exe的路径,\n可选添加任意个php-cgi.exe的启动参数
end intellisense**/