/*
 *  This file is part of DVS, a simple distributed versioning system
 *  See http://www.cs.colorado.edu/~carzanig/dvs/
 *
 *  Author: Antonio Carzaniga <carzanig@cs.colorado.edu>
 *
 *  Copyright (C) 1998-2002 University of Colorado
 *
 *  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
 *  of the License, 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., 59 Temple Place, Suite 330, Boston, MA 02111-1307,
 *  USA, or send email to carzanig@cs.colorado.edu.
 *
 *
 *  $Id: dirstack.c,v 1.2 2002/05/01 17:31:46 carzanig Exp $
 */
#include <stdlib.h>
#include <stdio.h>
#include <sys/param.h>
#include <errno.h>
#include <unistd.h>
#include <string.h>

#include "dirstack.h"

#ifndef MAXPATHLEN
#define MAXPATHLEN 1024
#endif

struct dirstack_s {
    char *dirname;
    struct dirstack_s *next;
};

static struct dirstack_s * DirStack=NULL;

int pushdir(const char *pathname)
{
    struct dirstack_s *newentry;
    char *currdir=NULL;

    if((newentry = malloc(sizeof(struct dirstack_s)))==NULL) {
	perror("Can't allocate new directory stack element");
	free(currdir);
	return -1;
    }
    if (pathname != NULL && *pathname != '\0' && strcmp(pathname,".")!=0) {
      if ((currdir = getcwd(NULL, MAXPATHLEN))==NULL) {
	perror("Can't get cwd.");
	free(newentry);
	return -1;
      }
      if (chdir(pathname)<0) {
        fprintf(stderr, "Could not chdir to `%s'.\n(%s)\n", 
	        pathname, strerror(errno));
	free(newentry);
	free(currdir);
	return -1;
      }
    }
    newentry->next = DirStack;
    DirStack = newentry;
    newentry->dirname = currdir;
    return 0;
}

int popdir()
{
    struct dirstack_s *aux;
    int result = 0;

    if (DirStack == NULL) {
        fprintf(stderr, "Empty dir stack.\n");
        return -1; 
    }
    if (DirStack->dirname != NULL && (result = chdir(DirStack->dirname))<0) {
      fprintf(stderr, "Could not chdir to `%s'.\n(%s)\n", 
	      DirStack->dirname, strerror(errno));
    };
    free(DirStack->dirname);
    aux = DirStack;
    DirStack = DirStack->next;
    free(aux);
    return result;
}
