/* ************************************************************************** */
/*                                                                            */
/*                                                        :::      ::::::::   */
/*   cd.c                                               :+:      :+:    :+:   */
/*                                                    +:+ +:+         +:+     */
/*   By: lperrey <lperrey@student.42.fr>            +#+  +:+       +#+        */
/*                                                +#+#+#+#+#+   +#+           */
/*   Created: 2021/12/04 19:31:19 by lperrey           #+#    #+#             */
/*   Updated: 2021/12/08 22:33:56 by lperrey          ###   ########.fr       */
/*                                                                            */
/* ************************************************************************** */

#include "minishell.h"

#define CMD "builtin_cd"

static int	change_prompt(t_all *c);
static int	change_env_pwd(void);

int	builtin_cd(int argc, char *argv[], t_all *c)
{
	char	*dir;

	if (argc > 2)
		return (shell_error("cd: ", "too many arguments", "", EXIT_FAILURE));
	else if (argc < 2 || ft_strncmp(argv[1], "~", 2) == 0)
	{
		dir = getenv("HOME");
		if (!dir)
			return (shell_error("cd: ", "HOME not set", "", EXIT_FAILURE));
	}
	else if (argc == 2)
		dir = argv[1];
	if (chdir(dir) == -1)
		return (shell_perror("cd: ", dir, ": ", EXIT_FAILURE));
	if (change_prompt(c) == -1)
		return (ft_reti_perror(EXIT_FAILURE, CMD", change_prompt()"));
	if (change_env_pwd() == -1)
		return (ft_reti_perror(EXIT_FAILURE, CMD", change_env_pwd()"));
	return (EXIT_SUCCESS);
}

static int	change_prompt(t_all *c)
{
	char	*tmp;

	tmp = init_prompt(c->prompt_base);
	if (!tmp)
		return (-1);
	free(c->prompt);
	c->prompt = tmp;
	return (0);
}

static int	change_env_pwd(void)
{
	char	*tmp;
	int		ret;

	tmp = getenv("PWD");
	if (tmp)
	{
		tmp = ft_strjoin("OLDPWD=", tmp);
		if (!tmp)
			return (-1);
		ret = export_var(tmp);
		free(tmp);
		if (ret == -1)
			return (-1);
	}
	tmp = getcwd(NULL, 0);
	if (!tmp)
		return (-1);
	tmp = ft_strjoinfree_s2("PWD=", tmp);
	if (!tmp)
		return (-1);
	ret = export_var(tmp);
	free(tmp);
	if (ret == -1)
		return (-1);
	return (0);
}
