/*
 * tilde.c : Tilde expansion for filenames
 *
 * George Ferguson, ferguson@cs.rochester.edu, 23 Apr 1993.
 * 13 May 1993: Cleanups.
 *  5 Jul 1994: Do it without modifying the stupid original.
 *
 */

#include <stdio.h>
#include <sys/types.h>
#include <pwd.h>
#include "config.h"
#ifdef HAVE_SYS_PARAM_H
# include <sys/param.h>
#endif
#include "alert.h"
#include "sysdefs.h"
#include "stringdefs.h"
extern uid_t getuid();		/* not in stdlib.h, but is in unistd.h */

char *
tildeExpand(file)
char *file;
{
    static char filename[MAXPATHLEN];
    char name[64];
    struct passwd *pwe;
    char *home;
    int i;

    /* Must start with tilde */
    if (*file != '~')
	return(file);
    /* Set default return value in case tilde expansion fails */
    strcpy(filename,file);
    /* Skip tilde */
    file += 1;
    /* Gather name following tilde (if any) */
    i = 0;
    while (*file != '\0' && *file != '/') {
	name[i++] = *file++;
    }
    name[i] = '\0';
    /* Skip slash (if any) */
    if (*file == '/') {
	file += 1;
    }
    if (*name == '\0') {				/* ~/... */
	if ((pwe=getpwuid(getuid())) != NULL) {
	    home = pwe->pw_dir;
	} else if ((home=getenv("HOME")) == NULL) {
	    alert0("Couldn't find homedir, you should set $HOME");
	    return(filename);
	}
    } else {						/* ~user/... */
	if ((pwe=getpwnam(name)) != NULL) {
	    home = pwe->pw_dir;
	} else {
	    alert1("Couldn't find homedir for \"%s\"",name);
	    return(filename);
	}
    }
    if (*file != '\0') {
	sprintf(filename,"%s/%s",home,file);
    } else {
	strcpy(filename,home);
    }
    return(filename);
}
