/* Copyright (C) 1999 Beau Kuiper

   This program is free software; you can redistribute it and/or modify
   it under the terms of the GNU General Public License as published by
   the Free Software Foundation; either version 2, or (at your option)
   any later version.

   This program is distributed in the hope that it will be useful,
   but WITHOUT ANY WARRANTY; without even the implied warranty of
   MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE.  See the
   GNU General Public License for more details.

   You should have received a copy of the GNU General Public License
   along with this program; if not, write to the Free Software
   Foundation, Inc., 675 Mass Ave, Cambridge, MA 02139, USA.  */

#include "ftpd.h"

/* this works correctly for all cased because rootdir has already been
   corrected using getcwd */

char *dir_getreal(FTPSTATE *peer)
{
	int a;
	char *dir = getcwd2();
	
	if (dir == NULL)
		return(NULL);
	
	a = strlen(peer->basedir);
	
	if (strncmp(peer->basedir, dir, a) == 0)
		return(dir);

	freewrapper(dir);
	errno = EACCES;
	return(NULL);
}	

/* a quicker way to get the virtual dir, replaces both
   dir_toreal and dir_tovirtual. Note that the caller
   must copy the result if it want's to change the
   source */
   
char *dir_getvirtual(FTPSTATE *peer, char *normaldir)
{
	int a, b;
	
	a = strlen(peer->basedir);
	b = strlen(normaldir);
	
	if (a == 0)
		return(normaldir);
	
	if (b == a)
		return("/");
	
	return(normaldir + a);
}

void dir_combine(FTPSTATE *peer, char **pwd, char *newdir)
{
	char *moddir, *nextpos, *curpos;
	
	reallocwrapper(strlen(newdir) + strlen(*pwd) 
		       + strlen(peer->homedir) + 3, (void *)pwd);

	moddir = *pwd + strlen(peer->basedir);
	
	/* if the directory is /, set it to nothing */
	if (moddir[1] == 0)
		moddir[0] = 0;
		
	if (newdir[0] == '/')		/* absolute filename */
	{
		/* make newdir relative and clear result */
		newdir++;
		moddir[0] = 0;
	}
	else if (newdir[0] == '~')
	{
		strcpy(moddir, peer->homedir);
		newdir++;
		if (newdir[0] == '/')
			newdir++;
	}
	
	curpos = newdir;
	
	do 
	{
		nextpos = strchr(curpos, '/');
		if (nextpos != NULL)
			*nextpos = 0;

		if (strcmp(curpos, "") == 0);
		else if (strcmp(curpos, ".") == 0);
		else if (strcmp(curpos, "..") == 0)
		{
			char *newpos = strrchr(moddir, '/');
			
			if (newpos)
				*newpos = 0;
		}
		else
		{
			strcat(moddir, "/");
			strcat(moddir, curpos);
		}
		
		if (nextpos)
		{
			/* repair earlier damage, set next component */
			*nextpos = '/';
			curpos = nextpos + 1;
		}
		else
			curpos = NULL;
	} while (curpos);
	
	/* if the result is nothing, then it means root dir, so say so */
	if ((*pwd)[0] == 0)
		strcpy(*pwd, "/");
}
