
#include "Webserv.hpp"

bool	Webserv::_is_cgi(Client *client)
{
	if (client->get_path().find("/cgi-bin/") != std::string::npos)
		return true;
	return false;
}

void	Webserv::_exec_cgi(Client *client)
{
	char**	env;

	env = _set_env(client);
	_exec_script(client, env);
//	_construct_response(client);
}

char*	Webserv::_dup_env(std::string var, std::string val = "")
{
	std::string str;

	str = var + "=" + val;
	return ( strdup(str.c_str()) );
}

char**	Webserv::_set_env(Client *client)
{
	char**	env = new char*[19];

	env[0]  = _dup_env("AUTH_TYPE");
	env[1]  = _dup_env("CONTENT_LENGTH", "665");
	env[2]  = _dup_env("CONTENT_TYPE");
	env[3]  = _dup_env("GATEWAY_INTERFACE");
	env[4]  = _dup_env("PATH_INFO");
	env[5]  = _dup_env("PATH_TRANSLATED");
	env[6]  = _dup_env("QUERY_STRING");
	env[7]  = _dup_env("REMOTE_ADDR");
	env[8]  = _dup_env("REMOTE_HOST", client->get_headers("Host")); // just test
	env[9]  = _dup_env("REMOTE_IDENT");
	env[10] = _dup_env("REMOTE_USER");
	env[11] = _dup_env("REQUEST_METHOD", ::http_methods_to_str(client->get_method()));
	env[12] = _dup_env("SCRIPT_NAME");
	env[13] = _dup_env("SERVER_NAME");
	env[14] = _dup_env("SERVER_PORT");
	env[15] = _dup_env("SERVER_PROTOCOL", client->get_version());
	env[16] = _dup_env("SERVER_SOFTWARE");
	env[17] = _dup_env("REDIRECT_STATUS");
	env[18] = NULL;

	return env;
}

void	Webserv::_exec_script(Client *client, char **env)
{
	int		save_stdout;
	char * const * nll = NULL;

	// save STDOUT
	save_stdout = dup(STDOUT_FILENO);
	// inside child process
	if (fork() == 0)
	{
		dup2(client->fd, STDOUT_FILENO);
//		execve("./srcs/cgi-bin/cgi_cpp.cgi", nll, client->env);
		execve("./srcs/cgi-bin/php-cgi", nll, env);
	}
	// inside parent process
	else
		waitpid(-1, NULL, 0);
	// restore stdout
	dup2(save_stdout, STDOUT_FILENO);
}

void	Webserv::_construct_client(Client *client)
{
	(void)client;
}

