/*
** 1998-09-02 -	This command is a bit special, actually. It is designed to be used as the
**		double-click action for directories. If run by a double click, it will attempt
**		to enter the directory clicked. Otherwise, it will enter the first selected
**		directory, if any.
** 1999-01-20 -	Added calls to the automount module at the relevant points.
** 1999-03-06 -	Rewritten to comply with new selection architecture. Way shorter.
** 1999-05-07 -	Added support for command argument specifying wanted directory.
** 1999-05-29 -	Remove one character, magically bringing support for symlinks back online. :)
*/

#include "gentoo.h"
#include "errors.h"
#include "dirpane.h"
#include "mount.h"
#include "strutil.h"

#include "cmd_direnter.h"

/* ----------------------------------------------------------------------------------------- */

/* 1999-05-07 -	Get the name of the first selected row of <dp>. If that is not a directory,
**		report error to user and return NULL.
*/
static const gchar * get_selected_dir(DirPane *dp)
{
	const gchar	*dir = NULL;
	GSList		*slist;

	if((slist = dp_get_selection(dp)) != NULL)
	{
		if(S_ISDIR(DP_SEL_STAT(slist).st_mode))
		{
			errno = 0;
			dir = DP_SEL_NAME(slist);
			dp_unselect(dp, DP_SEL_INDEX(dp, slist));
		}
		else
			errno = ENOTDIR;
		dp_free_selection(slist);
	}
	return dir;
}

/* 1999-05-07 -	Rewrote this, now supports a "dir" command argument. */
int cmd_direnter(MainInfo *min, DirPane *src, DirPane *dst, CmdArg *ca)
{
	const gchar	*dir;
	gchar		buf[PATH_MAX] = "";

	errno = 0;
	if((dir = car_bareword_get(ca, 0)) == NULL)
		dir = car_keyword_get_value(ca, "dir", NULL);
	if(dir == NULL)
		dir = get_selected_dir(src);

	if(dir != NULL)
	{
		if(dir[0] == '/')	/* Absolute? */
			str_strncpy(buf, dir, sizeof buf);
		else
		{
			if(strcmp(src->dir.path, "/") == 0)		/* Is pane in root? */
				g_snprintf(buf, sizeof buf, "/%s", dir);		/* Avoid double-slash. */
			else
				g_snprintf(buf, sizeof buf, "%s/%s", src->dir.path, dir);
		}
		mnt_entering(min, buf, MNT_RARELY);
		dp_enter_dir(src, buf);
	}
	if(errno != 0)
	{
		err_set(min, errno, "DirEnter", buf);
		err_show(min);
	}

	return (dir != NULL) && (errno == 0);
}

