/* ************************************************************************** */
/*                                                                            */
/*                                                        :::      ::::::::   */
/*   s_lredir.c                                         :+:      :+:    :+:   */
/*                                                    +:+ +:+         +:+     */
/*   By: rbousset <marvin@42.fr>                    +#+  +:+       +#+        */
/*                                                +#+#+#+#+#+   +#+           */
/*   Created: 2020/02/14 17:19:27 by rbousset          #+#    #+#             */
/*   Updated: 2020/02/14 17:19:29 by rbousset         ###   ########lyon.fr   */
/*                                                                            */
/* ************************************************************************** */

#include <libft.h>
#include <stdlib.h>
#include <string.h>
#include <fcntl.h>
#include <unistd.h>
#include <errno.h>
#ifdef __linux__
# include <linux/limits.h>
#else
# include <limits.h>
#endif

#include "d_define.h"
#include "s_struct.h"

static t_lredir	*s_lredir_last(struct s_lredir *lredir)
{
	while (lredir->next != NULL)
	{
		lredir = lredir->next;
	}
	return (lredir);
}

void			s_lredir_add_back(t_lredir **lredir, t_lredir *new)
{
	struct s_lredir	*tmp;

	if (*lredir == NULL)
	{
		*lredir = new;
	}
	else
	{
		tmp = s_lredir_last(*lredir);
		tmp->next = new;
	}
}

void			s_lredir_clear(struct s_lredir **lredir)
{
	struct s_lredir	*renext;
	struct s_lredir	*tmp;

	if (lredir == NULL)
		return ;
	tmp = *lredir;
	while (tmp != NULL)
	{
		renext = tmp->next;
		if (tmp->heredoc != NULL)
			ft_memdel((void*)&tmp->heredoc);
		ft_memdel((void*)&tmp);
		tmp = renext;
	}
	*lredir = NULL;
}

static int		s_get_right_fd(const char path[])
{
	char	*ptr;
	int		rfd;

	ptr = (char*)path;
	while (ft_isdigit(*ptr) == TRUE)
		ptr++;
	if (*ptr != C_NUL)
	{
		ft_dprintf(STDERR_FILENO, "minishell: %s: ambigous redirect\n", path);
		return (-1);
	}
	rfd = ft_atoi(path);
	if (fcntl(rfd, F_GETFD) == -1)
	{
		ft_dprintf(STDERR_FILENO, "minishell: %s: %s\n", path, strerror(errno));
		return (-1);
	}
	return (rfd);
}

struct s_lredir	*s_lredir_new(const char path[], int fd, char redir)
{
	struct s_lredir	*rdr;

	if ((rdr = (struct s_lredir*)malloc(sizeof(struct s_lredir))) == NULL)
		return (NULL);
	rdr->fd = fd;
	rdr->right_fd = -1;
	if (redir == 3 && (rdr->right_fd = s_get_right_fd(path)) == -1)
	{
		ft_memdel((void*)&rdr);
		return (NULL);
	}
	rdr->redir = redir;
	rdr->next = NULL;
	ft_strlcpy(rdr->path, path, PATH_MAX);
	return (rdr);
}