/* ************************************************************************** */
/*                                                                            */
/*                                                        :::      ::::::::   */
/*   redirect_process_heredoc.c                         :+:      :+:    :+:   */
/*                                                    +:+ +:+         +:+     */
/*   By: qmennen <qmennen@student.codam.nl>         +#+  +:+       +#+        */
/*                                                +#+#+#+#+#+   +#+           */
/*   Created: 2025/02/26 16:46:32 by qmennen           #+#    #+#             */
/*   Updated: 2025/02/26 16:54:09 by qmennen          ###   ########.fr       */
/*                                                                            */
/* ************************************************************************** */

#include "minishell.h"

/**
 * process_heredoc - Handles the processing of a heredoc in a minishell.
 * @msh: Pointer to the minishell structure.
 * @heredoc: Pointer to the token representing the heredoc.
 * @delim: Pointer to the token representing the delimiter.
 *
 * This function reads lines from the standard input until a line matching
 * the delimiter is encountered or an end-of-file (EOF) is reached. Each
 * line is expanded and written to a temporary file named ".ms_heredoc".
 * The function sets the type of the heredoc token to T_REDIRECT_IN and
 * updates the delimiter token's value to the temporary file's name.
 *
 * Return: 1 on success, or a negative value on failure.
 */
int	process_heredoc(t_minishell *msh, t_token *heredoc, t_token *delim)
{
	char		*line;
	char		*expand;
	const int	fd = open(".ms_heredoc", O_WRONLY | O_CREAT | O_TRUNC, 0644);

	if (fd < 0)
	{
		error_msg("heredoc", "unable to write to temp file");
		return (fd);
	}
	while (TRUE)
	{
		line = readline(">");
		if ((*line && ft_strcmp(line, delim->value) == 0) || !line)
			break ;
		if (!*line)
			ft_strlcat(line, "\n", 1);
		expand = expander_parse_string(line, msh);
		ft_putendl_fd(expand, fd);
		free_safe(msh, (void **)&expand);
		free(line);
	}
	close(fd);
	heredoc->type = T_REDIRECT_IN;
	delim->value = ft_strdup_safe(msh, ".ms_heredoc");
	return (free(line), 1);
}
