/*
 *  WindowMaker miscelaneous function library
 * 
 *  Copyright (c) 1997 Alfredo K. Kojima
 * 
 *  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., 675 Mass Ave, Cambridge, MA 02139, USA.
 */


#include <stdlib.h>
#include <unistd.h>
#include <string.h>
#include <pwd.h>

#include "wwmlib.h"

#ifdef WMAKER
extern void wAbort();
#endif

char*
gethomedir()
{
    char *home = getenv("HOME");
    struct passwd *user;

    if (home)
      return home;
    
    user = getpwuid(getuid());
    if (!user) {
	wSysError("could not get password entry for UID %i", getuid());
#ifdef WMAKER
	wAbort();
#endif
	exit(1);
    }
    if (!user->pw_dir) {
	return "/";
    } else {
	return user->pw_dir;
    }
}

/*
 *----------------------------------------------------------------------
 * find_file--
 * 	Finds a file in a : separated list of paths. ~ expansion is also 
 * done.
 * 
 * Returns:
 * 	The complete path for the file (in a newly allocated string) or
 * NULL if the file was not found.
 * 
 * Side effects:
 * 	A new string is allocated. It must be freed later.
 * 
 *---------------------------------------------------------------------- 
 */
char *
find_file(char *paths, char *file)
{
    char *path;
    char *tmp;
    int done;
    int len, flen;
    char *fullpath;

    if (!file)
	return NULL;
    if (*file=='/' || !paths) {
	if (access(file, R_OK)<0)
	  return NULL;
	return strdup(file);
    }
    flen = strlen(file);
    tmp = paths;
    done=0;
    while (!done) {
	len = strcspn(tmp, ":");
	if (len==0) done=1;
	path = xmalloc(len+flen+1);
	path = memcpy(path, tmp, len);
	path[len]=0;
	strcat(path, file);
	/* expand tilde */
	if (path[0]!='~') {
	    fullpath = path;
	} else {
	    /* home is statically allocated. Don't free it! */
	    char *home = gethomedir();

	    fullpath = xmalloc(strlen(home)+flen+len+2);
	    strcpy(fullpath, home);
	    strcat(fullpath, &(path[1]));
	    free(path);
	}
	if (access(fullpath, R_OK)==0) {
	    return fullpath;
	}
	free(fullpath);
	tmp=&(tmp[len+1]);
	if (*tmp==0) break;
    }
    return NULL;
}
