/* ************************************************************************** */
/*                                                                            */
/*                                                        :::      ::::::::   */
/*   p_redirs_heredoc.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 <stdint.h>
#include <unistd.h>

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

char	*p_get_heredoc(const char path[], t_msh *msh)
{
	char	*heredoc;
	char	*line;
	int8_t	gnl;

	line = NULL;
	heredoc = NULL;
	gnl = 1;
	if ((heredoc = ft_strdup("")) == NULL)
		return (NULL);
	while (gnl > 0)
	{
		if (msh->fd == STDIN_FILENO)
			m_prompt_psx(2, msh);
		gnl = get_next_line(msh->fd, &line);
		if (ft_strncmp(path, line, ft_strlen(path) + 1) == 0)
			break ;
		if ((heredoc = ft_nrealloc(heredoc, ft_strlen(heredoc) + 1,
			ft_strlen(heredoc) + ft_strlen(line) + 2)) == NULL)
			break ;
		ft_strlcpy(heredoc + ft_strlen(heredoc), line, ft_strlen(line) + 1);
		heredoc[ft_strlen(heredoc) + 1] = C_NUL;
		heredoc[ft_strlen(heredoc)] = C_LF;
		ft_memdel((void*)&line);

	}
	if (gnl > 0)
		ft_memdel((void*)&line);
	return (heredoc);
}