/* ************************************************************************** */
/*                                                                            */
/*                                                        ::::::::            */
/*   builtin_exit.c                                     :+:    :+:            */
/*                                                     +:+                    */
/*   By: qmennen <qmennen@student.codam.nl>           +#+                     */
/*                                                   +#+                      */
/*   Created: 2025/02/20 11:32:59 by whaffman      #+#    #+#                 */
/*   Updated: 2025/03/03 23:05:15 by whaffman      ########   odam.nl         */
/*                                                                            */
/* ************************************************************************** */

#include "minishell.h"

//TODO EXIT last exit status r:20
int	builtin_exit(t_minishell *msh, t_command *cmd)
{
	int	exit_status;

	exit_status = 0;
	if (ft_count_arr(cmd->args) > 2)
	{
		ft_putstr_fd("exit\n", STDOUT_FILENO);
		ft_putstr_fd("minishell: exit: too many arguments\n", STDERR_FILENO);
		return (EXIT_FAILURE);
	}
	if (ft_count_arr(cmd->args) == 2 && cmd->args[1] != NULL)
	{
		if (ft_isdigit_str(cmd->args[1]) == FALSE)
		{
			ft_putstr_fd("exit\n", STDOUT_FILENO);
			ft_putstr_fd("minishell: exit: ", STDERR_FILENO);
			ft_putstr_fd(cmd->args[1], STDERR_FILENO);
			ft_putstr_fd(": numeric argument required\n", STDERR_FILENO);
			return (2);
		}
		exit_status = ft_atoi(cmd->args[1]);
	}
	free_minishell(&msh);
	ft_putendl_fd("exit", STDOUT_FILENO);
	rl_clear_history();
	exit(exit_status);
}
