/* ************************************************************************** */
/*                                                                            */
/*                                                        ::::::::            */
/*   executor_child.c                                   :+:    :+:            */
/*                                                     +:+                    */
/*   By: qmennen <qmennen@student.codam.nl>           +#+                     */
/*                                                   +#+                      */
/*   Created: 2025/02/12 21:25:10 by willem        #+#    #+#                 */
/*   Updated: 2025/03/02 22:28:55 by whaffman      ########   odam.nl         */
/*                                                                            */
/* ************************************************************************** */

#include "minishell.h"

static int	is_dir(char *path)
{
	struct stat	path_stats;

	if (stat(path, &path_stats) < 0)
	{
		error_msg("is_dir", "path could not be read");
		return (0);
	}
	return (S_ISDIR(path_stats.st_mode));
}

static int validate_executable_path(char *path)
{
	if (access(path, X_OK) < 0)
	{
		error_msg(path, "Permission denied");
		return (0);
	}
	if (is_dir(path))
	{
		error_msg(path, "Is a directory");
		return (0);
	}
	return (1);
}

void	executor_child(t_minishell *msh, t_command *command)
{
	char	*path;

	if (command->fd_in != 0)
		dup2(command->fd_in, 0);
	if (command->fd_out != 1)
		dup2(command->fd_out, 1);
	executor_close_fds(command->n_fds);
	path = executor_absolute_path(msh, command->args[0]);
	if (path == NULL)
	{
		errno = 0;
		error_msg("minishell", "command not found");
		return ;
	}
	else if (! validate_executable_path(path))
		return ;
	execve(path, command->args, environment_get_arr(msh));
}
