/* ************************************************************************** */
/*                                                                            */
/*                                                        :::      ::::::::   */
/*   redirection.c                                      :+:      :+:    :+:   */
/*                                                    +:+ +:+         +:+     */
/*   By: cchauvet <cchauvet@student.42angouleme.fr  +#+  +:+       +#+        */
/*                                                +#+#+#+#+#+   +#+           */
/*   Created: 2023/03/27 13:44:22 by cchauvet          #+#    #+#             */
/*   Updated: 2023/03/29 19:19:51 by cchauvet         ###   ########.fr       */
/*                                                                            */
/* ************************************************************************** */

#include "redirection_private.h"

int	ft_replace_file(t_data *data, char **tab)
{
	size_t	i;
	char	*redirection;

	i = 0;
	while (tab[i] != NULL)
	{
		if (ft_is_in("<>", tab[i][0]))
		{
			i++;
			redirection = ft_env_filler(data, tab[i]);
			if (redirection == NULL)
				return (1);
			free(tab[i]);
			tab[i] = redirection;
			ft_quote_remover(tab[i]);
		}
		i++;
	}
	return (0);
}

static void	ft_skip(char *str, size_t *i, ssize_t *start)
{
	while (str[*i] == str[*start])
		(*i)++;
	while (str[*i] == ' ')
		(*i)++;
	while (str[*i] != '\0' && (str[*i] != ' '
			|| ft_is_in_quote(str, *i)))
		(*i)++;
}

static void	ft_remove_redirection(char *cmd_str)
{
	size_t	i;
	ssize_t	start;

	i = 0;
	while (cmd_str[i] != '\0')
	{
		start = -1;
		while ((ft_is_in_quote(cmd_str, i) || !ft_is_in("<>", cmd_str[i]))
			&& cmd_str[i] != '\0')
			i++;
		if (ft_is_in("<>", cmd_str[i]))
			start = i;
		else
			continue ;
		ft_skip(cmd_str, &i, &start);
		if (start != -1)
		{
			ft_strshift(cmd_str + start, -1 * (i - start));
			i = start;
		}
	}
}

int	ft_set_redirection(t_data *data, t_cmd *cmd, char **tab)
{
	size_t	i;

	i = 0;
	while (tab[i + 1] != NULL)
	{
		ft_quote_remover(tab[i + 1]);
		if (ft_check_redirection(data, cmd, tab[i], tab[i + 1]))
			return (1);
		i++;
	}
	return (0);
}

int	ft_redirection(t_data *data, t_cmd *cmd, char *cmd_str)
{
	char	**tab;

	cmd->fd_in[0] = -1;
	cmd->fd_in[1] = -1;
	cmd->fd_out[0] = -1;
	cmd->fd_out[1] = -1;
	tab = ft_split_quoted(cmd_str, ' ');
	if (tab == NULL)
	{
		ft_eprintf("minishell: malloc failed\n");
		return (1);
	}
	ft_remove_redirection(cmd_str);
	if (ft_set_redirection(data, cmd, tab))
	{
		ft_freer_tab_ultimate(1, tab);
		return (1);
	}
	ft_freer_tab_ultimate(1, tab);
	return (0);
}