/* ************************************************************************** */
/*                                                                            */
/*                                                        :::      ::::::::   */
/*   unset.c                                            :+:      :+:    :+:   */
/*                                                    +:+ +:+         +:+     */
/*   By: lperrey <lperrey@student.42.fr>            +#+  +:+       +#+        */
/*                                                +#+#+#+#+#+   +#+           */
/*   Created: 2021/12/05 17:05:05 by lperrey           #+#    #+#             */
/*   Updated: 2021/12/05 18:14:28 by lperrey          ###   ########.fr       */
/*                                                                            */
/* ************************************************************************** */

#include "minishell.h"

static int	unset_env_var(char *arg);

int	builtin_unset(int argc, char *argv[], t_all *c)
{
	int	i;
	int	exit_value;

	(void)argc;
	(void)c;
	exit_value = EXIT_SUCCESS;
	i = 1;
	while (argv[i])
	{
		if (unset_env_var(argv[i]) == EXIT_FAILURE)
			exit_value = EXIT_FAILURE;
		i++;
	}
	return (exit_value);
}

static int	unset_env_var(char *arg)
{
	int	env_position;

	if (!ft_is_posix_name(arg))
	{
		shell_error("unset: ", arg, ": not a valid identifier", 0);
		return (EXIT_FAILURE);
	}
	env_position = ft_getenv_position(arg);
	free(environ[env_position]);
	while (environ[env_position])
	{
		environ[env_position] = environ[env_position + 1];
		env_position++;
	}
	return (EXIT_SUCCESS);
}

/*
environment variables must be POSIX NAME :
	3.235 Name
https://pubs.opengroup.org/onlinepubs/9699919799/basedefs/V1_chap03.html
#tag_03_235
*/
