/* ************************************************************************** */
/*                                                                            */
/*                                                        :::      ::::::::   */
/*   shell_loop.c                                       :+:      :+:    :+:   */
/*                                                    +:+ +:+         +:+     */
/*   By: lperrey <lperrey@student.42.fr>            +#+  +:+       +#+        */
/*                                                +#+#+#+#+#+   +#+           */
/*   Created: 2021/10/04 05:59:26 by lperrey           #+#    #+#             */
/*   Updated: 2021/12/10 10:23:40 by hulamy           ###   ########.fr       */
/*                                                                            */
/* ************************************************************************** */

#include "minishell.h"

static char	*read_input(char *prompt, t_all *c);

void	shell_loop(t_all *c)
{
	char	*line_input;

	line_input = NULL;
	while (1)
	{
		if (line_input)
			free(line_input);
		line_input = read_input(c->prompt, c);
		if (line_input && *line_input)
		{
			add_history(line_input);
			c->token_list = lexing(line_input);
			ft_free_null(&line_input);
			if (!c->token_list)
				continue ;
			c->pipeline = parsing(c->token_list);
			ft_lstclear((t_list **)&c->token_list, free);
			if (!c->pipeline)
				continue ;
			exec_cmd_line(c);
		}
	}
}

static char	*read_input(char *prompt, t_all *c)
{
	char				*line_input;
	struct sigaction	signal_behaviour;

	ft_bzero(&signal_behaviour, sizeof signal_behaviour);
	signal_behaviour.sa_handler = sigint_handler_interactive;
	sigaction(SIGINT, &signal_behaviour, NULL);
	line_input = readline(prompt);
	signal_behaviour.sa_handler = SIG_IGN;
	sigaction(SIGINT, &signal_behaviour, NULL);
	if (!line_input)
	{
		write(STDERR_FILENO, "exit\n", 5);
		exit_free(c, get_last_exit_status());
	}
	return (line_input);
}
