/* ************************************************************************** */
/*                                                                            */
/*                                                        :::      ::::::::   */
/*   b_export.c                                         :+:      :+:    :+:   */
/*                                                    +:+ +:+         +:+     */
/*   By: rbousset <marvin@42.fr>                    +#+  +:+       +#+        */
/*                                                +#+#+#+#+#+   +#+           */
/*   Created: 2020/02/14 17:19:27 by rbousset          #+#    #+#             */
/*   Updated: 2020/02/14 17:19:29 by rbousset         ###   ########lyon.fr   */
/*                                                                            */
/* ************************************************************************** */

#include <libft.h>
#include <stdlib.h>
#include <stdint.h>

#include "b_env.h"
#include "b_export_next.h"
#include "d_enum.h"
#include "f_fail.h"
#include "s_destroy.h"
#include "s_line.h"
#include "s_lvars.h"
#include "s_struct.h"
#include "u_utils.h"
#include "u_vars.h"

t_bool		check_valid_identifier(const char arg[])
{
	char	*ptr;

	ptr = (char*)arg;
	if (ft_isalpha(ptr[0]) == TRUE || ptr[0] == '_')
	{
		return (TRUE);
	}
	return (FALSE);
}

t_bool		check_equals(const char *arg)
{
	char	*ptr;

	ptr = (char*)arg;
	while (*ptr != '\0')
	{
		if (*ptr == '=')
		{
			return (TRUE);
		}
		ptr++;
	}
	return (FALSE);
}

void		b_add_to_env_from_globals(const char varname[],
									const char var[],
									t_msh *msh)
{
	size_t	i;
	char	**nenvp;

	i = 0;
	while (msh->envp[i] != NULL)
		i++;
	if ((nenvp = (char**)malloc((i + 2) * sizeof(char*))) == NULL)
		f_alloc_and_destroy_msh(msh);
	i = 0;
	while (msh->envp[i] != NULL)
	{
		if ((nenvp[i] = ft_strdup(msh->envp[i])) == NULL)
			f_alloc_and_destroy_msh(msh);
		i++;
	}
	if ((nenvp[i] = ft_strdup(var)) == NULL)
		f_alloc_and_destroy_msh(msh);
	nenvp[i + 1] = 0;
	ft_delwords(msh->envp);
	lvars_delone(&msh->vars, varname);
	msh->envp = nenvp;
}

static void	b_classic_export(char *ptr[], t_msh *msh)
{
	char	varval[4096];
	char	fmt[4096];

	if (check_equals(*ptr) == FALSE)
	{
		ft_sprintf(fmt, "$%s", *ptr);
		u_get_custom_var(varval, fmt, 4096, msh);
		if (varval[0] != C_NUL)
		{
			ft_sprintf(fmt, "%s=%s", *ptr, varval);
			b_add_to_env_from_globals(*ptr, fmt, msh);
		}
	}
	else
	{
		b_export_with_equals(*ptr, msh);
	}
}

uint8_t		b_export(char *args[], t_msh *msh)
{
	char	**ptr;
	uint8_t	r;

	if (args[0] == NULL)
		return (b_env(NULL, msh));
	r = 0;
	ptr = args;
	while (*ptr != NULL)
	{
		if (check_valid_identifier(*ptr) == FALSE)
		{
			f_fail_identifier("export", *ptr);
			r = 1;
			ptr++;
			continue ;
		}
		b_classic_export(ptr, msh);
		ptr++;
	}
	return (r);
}