/* ************************************************************************** */
/*                                                                            */
/*                                                        ::::::::            */
/*   executor_execute_pipeline.c                        :+:    :+:            */
/*                                                     +:+                    */
/*   By: willem <willem@student.codam.nl>             +#+                     */
/*                                                   +#+                      */
/*   Created: 2025/02/12 21:25:02 by willem        #+#    #+#                 */
/*   Updated: 2025/03/05 13:10:59 by whaffman      ########   odam.nl         */
/*                                                                            */
/* ************************************************************************** */

#include "minishell.h"

static int	execute_builtin(t_minishell *msh, t_command *cmd)
{
	int	original_stdout;
	int	original_stdin;
	int	exit_status;

	original_stdin = dup(STDIN_FILENO);
	original_stdout = dup(STDOUT_FILENO);
	dup2(cmd->fd_in, STDIN_FILENO);
	dup2(cmd->fd_out, STDOUT_FILENO);
	signal_init_child();
	exit_status = builtin_router(msh, cmd);
	signal_init_minishell();
	close(cmd->fd_in);
	close(cmd->fd_out);
	dup2(original_stdin, STDIN_FILENO);
	dup2(original_stdout, STDOUT_FILENO);
	close(original_stdin);
	close(original_stdout);
	return (exit_status);
}

static void executor_execute_command(t_minishell *msh, t_command *cmd)
{
	if (cmd->args[0] != NULL && is_builtin(cmd->args[0]) >= 0)
		msh->exit_status = execute_builtin(msh, cmd);
	else if (cmd->args[0] != NULL)
		executor_fork(msh, cmd);
}

int	executor_execute_pipeline(t_minishell *msh)
{
	t_list		*current;
	pid_t		last_pid;
	int			exit_status;

	executor_create_pipes(msh);
	executor_create_redirects(msh);
	current = msh->commands;
	ft_lstiter(current, print_commands);
	last_pid = 0;
	while (current)
	{
		executor_execute_command(msh, (t_command *)current->content);
		current = current->next;
	}
	if (last_pid != 0)
	{
		waitpid(last_pid, &exit_status, 0);
		msh->exit_status = ((exit_status) & 0xff00) >> 8;
	}
	signal_init_minishell();
	return (msh->exit_status);
}
