/* ************************************************************************** */
/*                                                                            */
/*                                                        ::::::::            */
/*   builtin_cd.c                                       :+:    :+:            */
/*                                                     +:+                    */
/*   By: whaffman <whaffman@student.codam.nl>         +#+                     */
/*                                                   +#+                      */
/*   Created: 2025/02/20 11:33:07 by whaffman      #+#    #+#                 */
/*   Updated: 2025/03/03 21:42:47 by whaffman      ########   odam.nl         */
/*                                                                            */
/* ************************************************************************** */

#include "minishell.h"

static int	builtin_cd_change_directory(t_minishell *msh, char *path)
{
	char	*oldpwd;

	oldpwd = getcwd(NULL, 0);
	if (oldpwd == NULL)
		return (error_msg("cd", "getcwd failed"), EXIT_FAILURE);
	if (chdir(path) == -1)
		return (error_msg("cd", path), free(oldpwd), EXIT_FAILURE);
	environment_update(msh, "OLDPWD", oldpwd);
	free(oldpwd);
	path = getcwd(NULL, 0);
	environment_update(msh, "PWD", path);
	free(path);
	return (EXIT_SUCCESS);
}

int	builtin_cd(t_minishell *msh, t_command *cmd)
{
	t_environment	*env;
	char			*path;

	if (cmd->args[1] != NULL && cmd->args[2] != NULL)
		return (error_msg("cd", "too many arguments"), EXIT_FAILURE);
	if (cmd->args[1] == NULL)
	{
		env = environment_get(msh, "HOME");
		if (env == NULL || env->value == NULL)
			return (error_msg("cd", "HOME not set"), EXIT_FAILURE);
		path = env->value;
	}
	else if (ft_strcmp(cmd->args[1], "-") == 0)
	{
		env = environment_get(msh, "OLDPWD");
		if (env == NULL || env->value == NULL)
			return (error_msg("cd", "OLDPWD not set"), EXIT_FAILURE);
		path = env->value;
	}
	else
		path = cmd->args[1];
	return (builtin_cd_change_directory(msh, path));
}
