/* ************************************************************************** */
/*                                                                            */
/*                                                        ::::::::            */
/*   executor_absolute_path.c                           :+:    :+:            */
/*                                                     +:+                    */
/*   By: willem <willem@student.codam.nl>             +#+                     */
/*                                                   +#+                      */
/*   Created: 2025/02/08 17:00:24 by willem        #+#    #+#                 */
/*   Updated: 2025/03/02 22:20:30 by whaffman      ########   odam.nl         */
/*                                                                            */
/* ************************************************************************** */

#include "minishell.h"

static char	*resolve_relative(t_minishell *msh, char *cmd)
{
	char	*executable;

	executable = ft_strdup_safe(msh, cmd);
	if (!executable)
		return (NULL);
	return (executable);
}

static char	*resolve_path(t_minishell *msh, char *path, char *cmd)
{
	char	*executable;

	executable = malloc_safe(msh, ft_strlen(path) + ft_strlen(cmd) + 2);
	ft_strlcpy(executable, path, ft_strlen(path) + 1);
	ft_strlcat(executable, "/", ft_strlen(path) + 2);
	ft_strlcat(executable, cmd, ft_strlen(path) + ft_strlen(cmd) + 2);
	if (access(executable, F_OK) == 0)
		return (executable);
	free_safe(msh, (void **)&executable);
	return (NULL);
}

char	*executor_absolute_path(t_minishell *msh, char *cmd)
{
	char			**path;
	t_environment	*path_env;
	char			*executable;
	int				i;

	if (cmd[0] == '/' || cmd[0] == '.')
		return (resolve_relative(msh, cmd));
	path_env = environment_get(msh, "PATH");
	if (!path_env)
		return (NULL);
	path = ft_split_safe(msh, path_env->value, ':');
	i = 0;
	while (path[i] != NULL)
	{
		executable = resolve_path(msh, path[i], cmd);
		if (executable)
			return (executable);
		i++;
	}
	return (ft_free_arr_safe(msh, path), NULL);
}
