/* ************************************************************************** */
/*                                                                            */
/*                                                        :::      ::::::::   */
/*   simple_cmd_builtin.c                               :+:      :+:    :+:   */
/*                                                    +:+ +:+         +:+     */
/*   By: lperrey <lperrey@student.42.fr>            +#+  +:+       +#+        */
/*                                                +#+#+#+#+#+   +#+           */
/*   Created: 2021/11/16 01:57:38 by lperrey           #+#    #+#             */
/*   Updated: 2021/12/01 16:49:37 by lperrey          ###   ########.fr       */
/*                                                                            */
/* ************************************************************************** */

#include "minishell.h"

static int	restore_stdio(int stdin_dup, int stdout_dup);

int	simple_command_builtin(t_cmd *cmd, t_all *c)
{
	int	stdin_dup;
	int	stdout_dup;

	stdin_dup = 0;
	stdout_dup = 0;
	if (cmd->fd_in != STDIN_FILENO)
	{
		stdin_dup = dup(STDIN_FILENO);
		if (stdin_dup == -1)
			return (ft_reti_perror(EXIT_FAILURE, "dup()"));
		if (dup2(cmd->fd_in, STDIN_FILENO) == -1)
			return (ft_reti_perror(EXIT_FAILURE, "dup2()"));
	}
	if (cmd->fd_out != STDOUT_FILENO)
	{
		stdout_dup = dup(STDOUT_FILENO);
		if (stdout_dup == -1)
			return (ft_reti_perror(EXIT_FAILURE, "dup()"));
		if (dup2(cmd->fd_out, STDOUT_FILENO) == -1)
			return (ft_reti_perror(EXIT_FAILURE, "dup2()"));
	}
	set_last_exit_status(cmd->builtin_f(ft_2d_arrlen(cmd->argv), cmd->argv, c));
	if (!restore_stdio(stdin_dup, stdout_dup))
		return (EXIT_FAILURE);
	return (EXIT_SUCCESS);
}

static int	restore_stdio(int stdin_dup, int stdout_dup)
{
	if (stdin_dup)
	{
		if (dup2(stdin_dup, STDIN_FILENO) == -1)
			return (ft_reti_perror(0, "dup2()"));
		if (close(stdin_dup) == -1)
			return (ft_reti_perror(0, "close()"));
	}
	if (stdout_dup)
	{
		if (dup2(stdout_dup, STDOUT_FILENO) == -1)
			return (ft_reti_perror(0, "dup2()"));
		if (close(stdout_dup) == -1)
			return (ft_reti_perror(0, "close()"));
	}
	return (1);
}
