/* posh: src/builtins.c
   Copyright (C) 2003, 2004, 2005, 2006  Clint Adams

   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
   */

/*
 * posh built-in commands: posh_builtin_*
 */

#include "sh.h"
#include "ksh_stat.h"
#include <ctype.h>
#include <search.h>
#include "compat.h"

extern Tflag builtin_flag;
extern int uoptind;

static Tflag flagtmp; /* ugly */
static int pflagtmp, flagstmp; /* also ugly */

int posh_builtin_brkcont(int argc, char **argv, int flags)
{
	int n, quit, optc;
	struct env *ep, *last_ep = (struct env *) 0;
	char *arg;

	optind = 0;

	while ((optc = getopt(argc, argv, "")) != -1) {
		switch (optc) {
			case '?':
				return 1;
				break;
			default:
				bi_errorf("humza");
		}
	}

	arg = argv[optind];

	if (!arg)
		n = 1;
	else if (!bi_getn(arg, &n))
		return 1;
	quit = n;
	if (quit <= 0) {
		/* at&t ksh does this for non-interactive shells only - weird */
		bi_errorf("%s: bad value", arg);
		return 1;
	}

	/* Stop at E_NONE, E_PARSE, E_FUNC, or E_INCL */
	for (ep = e; ep && !STOP_BRKCONT(ep->type); ep = ep->oenv)
		if (ep->type == E_LOOP) {
			if (--quit == 0)
				break;
			ep->flags |= EF_BRKCONT_PASS;
			last_ep = ep;
		}

	if (quit) {
		/* at&t ksh doesn't print a message - just does what it
		 * can.  We print a message 'cause it helps in debugging
		 * scripts, but don't generate an error (ie, keep going).
		 */
		if (n == quit) {
			warningf(TRUE, "%s: cannot %s", argv[0], argv[0]);
			return 0; 
		}
		/* POSIX says if n is too big, the last enclosing loop
		 * shall be used.  Doesn't say to print an error but we
		 * do anyway 'cause the user messed up.
		 */
		last_ep->flags &= ~EF_BRKCONT_PASS;
		warningf(TRUE, "%s: can only %s %d level(s)",
			argv[0], argv[0], n - quit);
	}

	unwind(flags & POSH_BUILTIN_BREAK ? LBREAK : LCONTIN);
	/*NOTREACHED*/
}

/* dummy function, special case in comexec() */
int posh_builtin_builtin(int UNUSED(argc), char UNUSED(**argv), int UNUSED(flags))
{
	return 0;
}

int posh_builtin_cd(int argc, char **argv, int UNUSED(flags))
{
	int optc, noargc;
	int physical = 0;
	int cdnode;			/* was a node from cdpath added in? */
	int printpath = 0;		/* print where we cd'd? */
	int rval;
	struct tbl *pwd_s, *oldpwd_s;
	XString xs;
	char *xp;
	char *dir, *try, *pwd;
	int phys_path;
	char *cdpath;

	optind = 0;

	while ((optc = getopt(argc, argv, "LP")) != -1) {
		switch (optc) {
			case 'L':
				physical = 0;
				break;
			case 'P':
				physical = 1;
				break;
			case '?':
				break;
			default:
				bi_errorf("humza");
		}
	}

	argv += optind;
	noargc = argc - optind;

	pwd_s = global("PWD");
	oldpwd_s = global("OLDPWD");

	if (noargc == 0) {
		/* No arguments - go home */
		if ((dir = str_val(global("HOME"))) == null) {
			bi_errorf("no home directory (HOME not set)");
			return 1;
		}
	} else if (noargc == 1) {
		/* One argument: - or dir */
		dir = argv[0];
		if (strcmp(dir, "-") == 0) {
			dir = str_val(oldpwd_s);
			if (dir == null) {
				bi_errorf("no OLDPWD");
				return 1;
			}
			printpath++;
		}
	} else {
		bi_errorf("too many arguments");
		return 1;
	}

	Xinit(xs, xp, PATH, ATEMP);
	/* xp will have a bogus value after make_path() - set it to 0
	 * so that if it's used, it will cause a dump
	 */
	xp = (char *) 0;

	cdpath = str_val(global("CDPATH"));
	do {
		cdnode = make_path(current_wd, dir, &cdpath, &xs, &phys_path);
#ifdef S_ISLNK
		if (physical)
			rval = chdir(try = Xstring(xs, xp) + phys_path);
		else
#endif /* S_ISLNK */
		{
#ifndef CD_BREAKAGE
			simplify_path(Xstring(xs, xp));
			rval = chdir(try = Xstring(xs, xp));
#else
			char *simplified;

			simplified = canonicalize_file_name(Xstring(xs, xp));
			if (simplified != NULL) {
				rval = chdir(try = strdup(simplified));
				free(simplified);
			}
			else
				rval = -1;
#endif
		}
	} while (rval < 0 && cdpath != (char *) 0);

	if (rval < 0) {
		if (cdnode)
			bi_errorf("%s: bad directory", dir);
		else
			bi_errorf("%s - %s", try, strerror(errno));
		return 1;
	}

	/* Set OLDPWD (note: unsetting OLDPWD does not disable this
	 * setting in at&t ksh)
	 */
	if (current_wd[0])
		/* Ignore failure (happens if readonly or integer) */
		setstr(oldpwd_s, current_wd, KSH_RETURN_ERROR);

	if (!ISABSPATH(Xstring(xs, xp))) {
		pwd = (char *) 0;
	} else
#ifdef S_ISLNK
		if (!physical || !(pwd = canonicalize_file_name(Xstring(xs, xp))))
#endif /* S_ISLNK */
			pwd = Xstring(xs, xp);

	/* Set PWD */
	if (pwd) {
		char *ptmp = pwd;
		set_current_wd(ptmp);
		/* Ignore failure (happens if readonly or integer) */
		setstr(pwd_s, ptmp, KSH_RETURN_ERROR);
	} else {
		set_current_wd(null);
		pwd = Xstring(xs, xp);
		/* XXX unset $PWD? */
	}
	if (printpath || cdnode)
		shprintf("%s\n", pwd);

	return 0;
}

/* :, false and true */
int posh_builtin_colon(int UNUSED(argc), char UNUSED(**argv), int flags)
{
	return (flags & POSH_BUILTIN_FALSE) ? 1 : 0;
}

/* Deal with command -vV - command -p dealt with in comexec() */
int posh_builtin_command(int UNUSED(argc), char UNUSED(**argv), int UNUSED(flags))
{
	return 1;
}

int posh_builtin_dot(int UNUSED(argc), char UNUSED(**argv), int UNUSED(flags))
{
	int optc;
	char *file, *cp;
	int i;
	int err;

	optind = 0;

	while ((optc = getopt(argc, argv, "")) != -1) {
		switch (optc) {
			case '?':
				return 1;
			default:
				bi_errorf("humza");
		}
	}

	argv += optind;
	argc -= optind;

	if ((cp = *argv) == NULL) {
		bi_errorf("no file specified for sourcing");
		return 1;
	}
	file = search(cp, path, R_OK, &err);
	if (file == NULL) {
		bi_errorf("%s: %s", cp, err ? strerror(err) : "not found");
		return 1;
	}

	/* Set positional parameters? */
	if (argv[1]) {
		argv[0] = e->loc->argv[0]; /* preserve $0 */
	}
	else {
		argv = (char **) 0;
		argc = 0;
	}
	i = include(file, argc, argv, 0);
	if (i < 0) { /* should not happen */
		bi_errorf("%s: %s", cp, strerror(errno));
		return 1;
	}
	return i;
}

int posh_builtin_echo(int UNUSED(argc), char **argv, int UNUSED(flags))
{
	int fd = 1;
	int newline = 1, nflags = 1;
	char *s;
	XString xs;
	char *xp, **wp;

	wp = argv;

	/* A compromise between SUSv3 and BSD echo commands:
	 * escape sequences are enabled by default, and
	 * -n is recognized if it appears in arguments with
	 * no illegal options (ie, echo -nq will print -nq).
	 * Different from sysV echo since options are recognized,
	 * different from BSD echo since escape sequences are enabled
	 * by default.
	 */
	wp += 1;
	while ((s = *wp) && *s == '-' && s[1]) {
		while (*++s)
			if (*s == 'n')
				nflags = 0;
			else
				/* bad option: don't use nflags, print
				 * argument
				 */
				break;
		if (*s)
			break;
		wp++;
		newline = nflags;
	}

	Xinit(xs, xp, 128, ATEMP);

	while (*wp != NULL) {
		int c;
		s = *wp;
		while ((c = *s++) != '\0') {
			Xcheck(xs, xp);
			if (c == '\\') {
				int i;

				switch ((c = *s++)) {
					/* Oddly enough, \007 seems more portable than
					 * \a (due to HP-UX cc, Ultrix cc, old pcc's,
					 * etc.).
					 */
					case 'a': c = '\007'; break;
					case 'b': c = '\b'; break;
					case 'c': newline = 0;
						  continue; /* AT&T brain damage */
					case 'f': c = '\f'; break;
					case 'n': c = '\n'; break;
					case 'r': c = '\r'; break;
					case 't': c = '\t'; break;
					case 'v': c = 0x0B; break;
					case '0':
						  /* Look for an octal number: can have
						   * three digits (not counting the
						   * leading 0).  Truely burnt.
						   */
						  c = 0;
						  for (i = 0; i < 3; i++) {
							  if (*s >= '0' && *s <= '7')
								  c = c*8 + *s++ - '0';
							  else
								  break;
						  }
						  break;
					case '\0': s--; c = '\\'; break;
					case '\\': break;
					default:
						   Xput(xs, xp, '\\');
				}
			}
			Xput(xs, xp, c);
		}
		if (*++wp != NULL)
			Xput(xs, xp, ' ');
	}
	if (newline)
		Xput(xs, xp, '\n');

	{
		int n, len = Xlength(xs, xp);
		for (s = Xstring(xs, xp); len > 0; ) {
			n = write(fd, s, len);
			if (n < 0) {
				if (errno == EINTR) {
					/* allow user to ^C out */
					intrcheck();
					continue;
				}
				return 1;
			}
			s += n;
			len -= n;
		}
	}

	return 0;
}

/* no-args exec (args exec special-cased in comexec) */
int posh_builtin_exec(int UNUSED(argc), char UNUSED(**argv), int UNUSED(flags))
{
	int i;

	/* make sure redirects stay in place */
	if (e->savefd != NULL) {
		for (i = 0; i < NUFILE; i++) {
			if (e->savefd[i] > 0)
				close(e->savefd[i]);
		}
		e->savefd = NULL; 
	}
	return 0;
}

int posh_builtin_exitreturn(int argc, char **argv, int flags)
{
	int how = LEXIT;
	int n, optc;
	char *arg;

	optind = 0;

	while ((optc = getopt(argc, argv, "")) != -1) {
		switch (optc) {
		  case '?':
			return 1;
		}
	}

	arg = argv[optind];

	if (arg) {
	    if (!getn(arg, &n)) {
		    exstat = 1;
		    warningf(TRUE, "%s: bad number", arg);
	    } else
		    exstat = n;
	}
	if (flags & POSH_BUILTIN_RETURN) { /* return */
		struct env *ep;

		/* need to tell if this is exit or return so trap exit will
		 * work right (POSIX)
		 */
		for (ep = e; ep; ep = ep->oenv)
			if (STOP_RETURN(ep->type)) {
				how = LRETURN;
				break;
			}
	}

	if (how == LEXIT && !really_exit && j_stopped_running()) {
		really_exit = 1;
		how = LSHELL;
	}

	quitenv();	/* get rid of any i/o redirections */
	unwind(how);
	/*NOTREACHED*/
	return 0;
}

static void ers_walk(const void *nodep, const VISIT which, const int UNUSED(depth)) {
	struct tbl *vp;

	switch(which) {
		case preorder:
		case endorder:
			break;
		case postorder:
		case leaf:
			vp = *(struct tbl **)nodep;
			struct tbl *tvp;
			int any_set = 0;
			/*
			 * See if the parameter is set (for arrays, if any
			 * element is set).
			 */
			for (tvp = vp; tvp; tvp = tvp->u.array)
				if (tvp->flag & ISSET) {
					any_set = 1;
					break;
				}
			/*
			 * Check attributes - note that all array elements
			 * have (should have?) the same attributes, so checking
			 * the first is sufficient.
			 *
			 * Report an unset param only if the user has
			 * explicitly given it some attribute (like export);
			 * otherwise, after "echo $FOO", we would report FOO...
			 */
			if (!any_set && !(vp->flag & USERATTRIB))
				return;
			if (flagtmp && (vp->flag & flagtmp) == 0)
				return;
			for (; vp; vp = vp->u.array) {
				/* Ignore array elements that aren't set unless there
				 * are no set elements, in which case the first is
				 * reported on
				 */
				if ((vp->flag&ARRAY) && any_set && !(vp->flag & ISSET))
					return;
				/* no arguments */
#if 0
				if (!(flagstmp & POSH_BUILTIN_SET)) {
					/* at&t ksh prints things like export, integer,
					 * leftadj, zerofill, etc., but POSIX says must
					 * be suitable for re-entry...
					 */
					if ((vp->flag&EXPORT) && (flagstmp & POSH_BUILTIN_EXPORT))
						shprintf("export %s\n", vp->name);
					else if ((vp->flag&RDONLY) && (flagstmp & POSH_BUILTIN_READONLY))
						shprintf("readonly %s\n", vp->name);
				} else {
#endif
					if (pflagtmp)
						shprintf("%s ",
								(flagtmp & EXPORT) ?  "export" : "readonly");
					if ((vp->flag&ARRAY) && any_set)
						shprintf("%s[%d]", vp->name, vp->index);
					else
						shprintf("%s", vp->name);
					if (vp->flag&ISSET && pflagtmp) {
						char *s = str_val(vp);

						shprintf("=");
						/* at&t ksh can't have justified integers.. */
						shprintf("%s", s);
					}
					shprintf("\n");
#if 0
				}
#endif
				/* Only report first `element' of an array with
				 * no set elements.
				 */
				if (!any_set)
					break;
			}
	}
}


int posh_builtin_exportreadonlyset(int argc, char **argv, int flags)
{
	struct block *l = e->loc;
	Tflag fset = 0, fclr = 0;
	int optc;
	Tflag flag;
	int pflag = 0;

	if(flags & POSH_BUILTIN_EXPORT)
		fset |= EXPORT;
	if(flags & POSH_BUILTIN_READONLY)
 		fset |= RDONLY;

	optind = 0;

	while ((optc = getopt(argc, argv, "p")) != -1) {
		switch (optc) {
		  case 'p':
			pflag = 1;
			break;
		  case '?':
			return 1;
		}
	}

	/* set variables and attributes */
	if (argv[optind]) {
		int i;
		int rval = 0;

		for (i = optind; argv[i]; i++) {
			if (!typeset(argv[i], fset, fclr, 0, 0)) {
				bi_errorf("%s: not identifier", argv[i]);
				return 1;
			}
		}
		return rval;
	}

	/* list variables and attributes */
	flag = fset | fclr; /* no difference at this point.. */
	
	    for (l = e->loc; l; l = l->next) {
		    flagtmp = flag;
		    flagstmp = flags;
		    pflagtmp = pflag;
		    twalk(l->vars.root, ers_walk);
	    }
	return 0;
}

int posh_builtin_local(int argc, char **argv, int UNUSED(flags))
{
	int i;
	char *p;

	if(!argv[1])
		return 1;

	for (i = 1; i < argc; i++) {
		for (p = argv[i]; *p; p++) {
			if (!typeset(argv[i], LOCAL, 0, 0, 0)) {
				bi_errorf("%s: not identifier", argv[i]);
				return 1;
			}
		}
	}

	return 0;
}

int posh_builtin_eval(int argc, char **argv, int UNUSED(flags))
{
	struct source *s,*olds=source;
	int retval, optc, errexitflagtmp;

	optind = 0;

	while ((optc = getopt(argc, argv, "+")) != -1) {
		switch (optc) {
		  case '?':
			return 1;
			break;
		}
	}

	s = pushs(SWORDS, ATEMP);
	s->u.strv = argv + optind;

	errexitflagtmp = Flag(FERREXIT);
	Flag(FERREXIT) = 0;
	retval=shell(s, FALSE);
	Flag(FERREXIT) = errexitflagtmp;
	source=olds;
	return retval;
}

int posh_builtin_getopts(int UNUSED(argc), char **argv, int UNUSED(flags))
{
	int	noargc, optc, ret, noerror;
	const char *options;
	const char *var;
	char	buf[3];
	char **wp;
	struct tbl *vq, *voptarg;

	wp = argv+1;
	optind = uoptind;

	options = *wp++;
	if (!options) {
		bi_errorf("missing options argument");
		return (1);
	}

	var = *wp++;
	if (!var) {
		bi_errorf("missing name argument");
		return (1);
	}
	if (!*var || *skip_varname(var, TRUE)) {
		bi_errorf("%s: is not an identifier", var);
		return (1);
	}

	if (e->loc->next == NULL) {
		internal_errorf(0, "posh_builtin_getopts: no argv");
		return (1);
	}

	noerror = (options[0] == ':') ? 1 : 0;
	opterr = !noerror;
	if (noerror)
		options++;

	/* Which arguments are we parsing... */
	if (*wp == NULL)
		wp = e->loc->next->argv;
	else
		*--wp = e->loc->next->argv[0];

	/* Check that our saved state won't cause a core dump... */
	for (noargc = 0; wp[noargc]; noargc++)
		;
	if (optind > noargc)
	{
	      bi_errorf("arguments changed since last call");
	      return 1;
	}

	optc = getopt(noargc, wp, options);

	voptarg = global("OPTARG");
	voptarg->flag &= ~RDONLY;	/* at&t ksh clears ro and int */
	/* Paranoia: ensure no bizarre results. */
//	if (voptarg->flag & INTEGER)
//	    typeset("OPTARG", 0, INTEGER, 0, 0);
	if (noerror && (optc == '?')) {
		buf[0]=optopt;
		buf[1]= '\0';
		setstr(voptarg, buf, KSH_RETURN_ERROR);
	}
	else if (optarg == (char *) 0)
		unset(voptarg, 0);
	else
		/* This can't fail (have cleared readonly/integer) */
		setstr(voptarg, optarg, KSH_RETURN_ERROR);

	ret = 0;

		/* POSIX says var is set to ? at end-of-options, at&t ksh
		 * sets it to null - we go with POSIX...
		 */

		buf[0] = optc < 0 ? '?' : optc;
		buf[1] = '\0';

	vq = global(var);
	/* Error message already printed (integer, readonly) */
	if (!setstr(vq, buf, KSH_RETURN_ERROR))
	    ret = 1;
	if (Flag(FEXPORT))
		typeset(var, EXPORT, 0, 0, 0);

	uoptind = optind;

	return (optc < 0 ? 1 : ret);
}

#if 0
int posh_builtin_kill(int argc, char **argv, int UNUSED(flags))
{
	Trap *t = (Trap *) 0;
	char *p;
	int lflag = 0;
	int i, n, rv, sig;
	int optc;

	optind = 0;

	while ((optc = getopt(argc, argv, "ls:")) != -1) {
		switch (optc) {
			  case 'l':
				lflag = 1;
				break;
			  case 's':
				if (!(t = gettrap(optarg))) {
					bi_errorf("bad signal `%s'",
						optarg);
					return 1;
				}
				break;		
			  case '?':
				return 1;
			}
	}
	i = 0;
	argv += optind;

	if ((lflag && t) || (!argv[i] && !lflag)) {
		shf_fprintf(shl_out,
"Usage: kill -s signame {pid|job}...\n\
       kill -l [exit_status]\n"
			);
		bi_errorf(null);
		return 1;
	}

	if (lflag) {
		if (argv[i]) {
			for (; argv[i]; i++) {
				if (!bi_getn(argv[i], &n))
					return 1;
				if (n > 128 && n < 128 + SIGNALS)
					n -= 128;
				if (n > 0 && n < SIGNALS && sigtraps[n].name)
					shprintf("%s\n", sigtraps[n].name);
				else
					shprintf("%d\n", n);
			}
		} else {
			p = null;
			for (i = 1; i < SIGNALS; i++, p = " ")
				if (sigtraps[i].name)
					shprintf("%s%s", p, sigtraps[i].name);
			shprintf("\n");
		}
		return 0;
	}
	rv = 0;
	sig = t ? t->signal : SIGTERM;
	for (; (p = argv[i]); i++) {
		if (*p == '%') {
			if (j_kill(p, sig))
				rv = 1;
		} else if (!getn(p, &n)) {
			bi_errorf("%s: arguments must be jobs or process ids",
				p);
			rv = 1;
		} else {
			/* use killpg if < -1 since -1 does special things for
			 * some non-killpg-endowed kills
			 */
			if ((n < -1 ? killpg(-n, sig) : kill(n, sig)) < 0) {
				bi_errorf("%s: %s", p, strerror(errno));
				rv = 1;
			}
		}
	}
	return rv;
}
#endif

int posh_builtin_pwd(int argc, char **argv, int UNUSED(flags))
{
	int optc, physical = 0;
	char *p, **wp;

	optind = 0;

	while ((optc = getopt(argc, argv, "LP")) != -1)
		switch (optc) {
			case 'L':
				physical = 0;
				break;
			case 'P':
				physical = 1;
				break;
			case '?':
				return 1;
		}

	wp = argv + optind;

	if (wp[0]) {
		bi_errorf("too many arguments");
		return 1;
	}
#ifdef S_ISLNK
	p = current_wd[0] ? (physical ? canonicalize_file_name(current_wd) : current_wd)
		: (char *) 0;
#else /* S_ISLNK */
	p = current_wd[0] ? current_wd : (char *) 0;
#endif /* S_ISLNK */
	if (p && eaccess(p, R_OK) < 0)
		p = (char *) 0;
	if (!p) {
		p = get_current_dir_name();
		if (!p) {
			bi_errorf("can't get current directory - %s",
					strerror(errno));
			return 1;
		}
	}
	shprintf("%s\n", p);
	return 0;
}

int posh_builtin_read(int argc, char **argv, int UNUSED(flags))
{
	int c = 0, expand = 1, expanding, ecode = 0;
	char *cp, **wp;
	int fd = 0;
	struct shf *shf;
	int optc;
	XString cs;
	struct tbl *vp;

	optind = 0;

	while ((optc = getopt(argc, argv, "r")) != -1)
		switch (optc) {
			case 'r':
				expand = 0;
				break;
			case '?':
				return 1;
		}
	wp = argv + optind;
	if ((argc - optind) < 1) {
		bi_errorf("mandatory argument is missing");
		return 1;
	}

	/* Since we can't necessarily seek backwards on non-regular files,
	 * don't buffer them so we can't read too much.
	 */
	shf = shf_reopen(fd, SHF_RD | SHF_INTERRUPT | can_seek(fd), shl_spare);

	if ((cp = strchr(*wp, '?')) != NULL) {
		*cp = 0;
		if (isatty(fd)) {
			/* at&t ksh says it prints prompt on fd if it's open
			 * for writing and is a tty, but it doesn't do it
			 * (it also doesn't check the interactive flag,
			 * as is indicated in the Kornshell book).
			 */
			shellf("%s", cp+1);
		}
	}

	expanding = 0;
	Xinit(cs, cp, 128, ATEMP);
	for (; *wp != NULL; wp++) {
		for (cp = Xstring(cs, cp); ; ) {
			if (c == '\n' || c == EOF)
				break;
			while (1) {
				c = shf_getc(shf);
				if (c == '\0'
#ifdef OS2
						|| c == '\r'
#endif /* OS2 */
				   )
					continue;
				if (c == EOF && shf_error(shf)
						&& shf_errno(shf) == EINTR)
				{
					/* Was the offending signal one that
					 * would normally kill a process?
					 * If so, pretend the read was killed.
					 */
					ecode = fatal_trap_check();

					/* non fatal (eg, CHLD), carry on */
					if (!ecode) {
						shf_clearerr(shf);
						continue;
					}
				}
				break;
			}
			Xcheck(cs, cp);
			if (expanding) {
				expanding = 0;
				if (c == '\n') {
					c = 0;
					if (Flag(FTALKING_I) && isatty(fd)) {
						/* set prompt in case this is
						 * called from .profile or $ENV
						 */
						set_prompt(PS2, (Source *) 0);
						pprompt(prompt, 0);
					}
				} else if (c != EOF)
					Xput(cs, cp, c);
				continue;
			}
			if (expand && c == '\\') {
				expanding = 1;
				continue;
			}
			if (c == '\n' || c == EOF)
				break;
			if (ctype(c, C_IFS)) {
				if (Xlength(cs, cp) == 0 && ctype(c, C_IFSWS))
					continue;
				if (wp[1])
					break;
			}
			Xput(cs, cp, c);
		}
		/* strip trailing IFS white space from last variable */
		if (!wp[1])
			while (Xlength(cs, cp) && ctype(cp[-1], C_IFS)
					&& ctype(cp[-1], C_IFSWS))
				cp--;
		Xput(cs, cp, '\0');
		vp = global(*wp);
		/* Must be done before setting export. */
		if (vp->flag & RDONLY) {
			shf_flush(shf);
			bi_errorf("%s is read only", *wp);
			return 1;
		}
		if (Flag(FEXPORT))
			typeset(*wp, EXPORT, 0, 0, 0);
		if (!setstr(vp, Xstring(cs, cp), KSH_RETURN_ERROR)) {
			shf_flush(shf);
			return 1;
		}
	}

	shf_flush(shf);

	return ecode ? ecode : c == EOF;
}

int posh_builtin_set(int UNUSED(argc), char **argv, int UNUSED(flags))
{
	int argi, setargs;
	struct block *l = e->loc;
	char **owp = argv;

	if (argv[1] == NULL) {
		static const char *const args [] = { "set", NULL };
		return posh_builtin_exportreadonlyset(1,(char **) args, POSH_BUILTIN_SET);
	}

	argi = parse_args(argv, OF_SET, &setargs);
	if (argi < 0)
		return 1;
	/* set $# and $* */
	if (setargs) {
		owp = argv += argi - 1;
		argv[0] = l->argv[0]; /* save $0 */
		while (*++argv != NULL)
			*argv = str_save(*argv, &l->area);
		l->argc = argv - owp - 1;
		l->argv = (char **) alloc(sizeofN(char *, l->argc+2), &l->area);
		for (argv = l->argv; (*argv++ = *owp++) != NULL; )
			;
	}
	/* POSIX says set exit status is 0, but old scripts that use
	 * getopt(1), use the construct: set -- `getopt ab:c "$@"`
	 * which assumes the exit value set will be that of the ``
	 * (subst_exstat is cleared in execute() so that it will be 0
	 * if there are no command substitutions).
	 */
	return 0;
}

int posh_builtin_shift(int argc, char **argv, int UNUSED(flags))
{
	struct block *l = e->loc;
	int n, optc, noargc;
	long val;
	char *arg;

	optind = 0;

	while ((optc = getopt(argc, argv, "")) != -1) {
		switch (optc) {
			default:
				bi_errorf("shiftza");
		}
	}
	argv += optind;
	noargc = argc - optind;

	if ((arg = *argv)) {
		evaluate(arg, &val, KSH_UNWIND_ERROR);
		n = val;
	} else
		n = 1;
	if (n < 0) {
		bi_errorf("%s: bad number", arg);
		return (1);
	}
	if (l->argc < n) {
		bi_errorf("nothing to shift");
		return (1);
	}
	l->argv[n] = l->argv[0];
	l->argv += n;
	l->argc -= n;
	return 0;
}

int posh_builtin_trap(int argc, char **argv, int UNUSED(flags))
{
	int i, optc;
	char *s;
	Trap *p;

	optind = 0;

	while ((optc = getopt(argc, argv, "")) != -1) {
		switch (optc) {
			case '?':
				return 1;
			default:
				bi_errorf("shiftza");
		}
	}
	argv += optind;

	if (*argv == NULL) {
		int anydfl = 0;

		for (p = sigtraps, i = SIGNALS+1; --i >= 0; p++) {
			if (p->trap == NULL)
				anydfl = 1;
			else {
				shprintf("trap -- ");
				print_value_quoted(p->trap);
				shprintf(" %s\n", p->name);
			}
		}
#if 0 /* this is ugly and not clear POSIX needs it */
		/* POSIX may need this so output of trap can be saved and
		 * used to restore trap conditions
		 */
		if (anydfl) {
			shprintf("trap -- -");
			for (p = sigtraps, i = SIGNALS+1; --i >= 0; p++)
				if (p->trap == NULL && p->name)
					shprintf(" %s", p->name);
			shprintf(newline);
		}
#endif
		return 0;
	}

	/*
	 * Use case sensitive lookup for first arg so the
	 * command 'exit' isn't confused with the pseudo-signal
	 * 'EXIT'.
	 */
	s = *argv++; /* get command */
	if (s != NULL && s[0] == '-' && s[1] == '\0')
		s = NULL;

	if (*argv == NULL) {
		bi_errorf("no signals specified");
		return 1;
	}

	/* set/clear traps */
	while (*argv != NULL) {
		p = gettrap(*argv++);
		if (p == NULL) {
			warningf(TRUE, "bad signal %s, not setting trap", argv[-1]);
			return 1;
		}
		settrap(p, s);
	}
	return 0;
}

int posh_builtin_umask(int argc, char **argv, int UNUSED(flags))
{
	int i;
	char *cp;
	int symbolic = 0;
	int old_umask, optc, noargc;

	optind = 0;

	while ((optc = getopt(argc, argv, "S")) != -1) {
		switch (optc) {
			case 'S':
				symbolic = 1;
				break;
			case '?':
				return 1;
		}
	}

	argv += optind;
	noargc = argc - optind;

	cp = *argv;
	if (cp == NULL) {
		old_umask = umask(0);
		umask(old_umask);
		if (symbolic) {
			char buf[18];
			int j;

			old_umask = ~old_umask;
			cp = buf;
			for (i = 0; i < 3; i++) {
				*cp++ = "ugo"[i];
				*cp++ = '=';
				for (j = 0; j < 3; j++)
					if (old_umask & (1 << (8 - (3*i + j))))
						*cp++ = "rwx"[j];
				*cp++ = ',';
			}
			cp[-1] = '\0';
			shprintf("%s\n", buf);
		} else
			shprintf("%#3.3o\n", old_umask);
	} else {
		int new_umask;

		if (isdigit(*cp)) {
			for (new_umask = 0; *cp >= '0' && *cp <= '7'; cp++)
				new_umask = new_umask * 8 + (*cp - '0');
			if (*cp) {
				bi_errorf("bad number");
				return 1;
			}
		} else {
			/* symbolic format */
			int positions, new_val;
			char op;

			old_umask = umask(0);
			umask(old_umask); /* in case of error */
			old_umask = ~old_umask;
			new_umask = old_umask;
			positions = 0;
			while (*cp) {
				while (*cp && strchr("augo", *cp))
					switch (*cp++) {
						case 'a': positions |= 0111; break;
						case 'u': positions |= 0100; break;
						case 'g': positions |= 0010; break;
						case 'o': positions |= 0001; break;
					}
				if (!positions)
					positions = 0111; /* default is a */
				if (!strchr("=+-", op = *cp))
					break;
				cp++;
				new_val = 0;
				while (*cp && strchr("rwxugoXs", *cp))
					switch (*cp++) {
						case 'r': new_val |= 04; break;
						case 'w': new_val |= 02; break;
						case 'x': new_val |= 01; break;
						case 'u': new_val |= old_umask >> 6;
							  break;
						case 'g': new_val |= old_umask >> 3;
							  break;
						case 'o': new_val |= old_umask >> 0;
							  break;
						case 'X': if (old_umask & 0111)
								  new_val |= 01;
							  break;
						case 's': /* ignored */
							  break;
					}
				new_val = (new_val & 07) * positions;
				switch (op) {
					case '-':
						new_umask &= ~new_val;
						break;
					case '=':
						new_umask = new_val
							| (new_umask & ~(positions * 07));
						break;
					case '+':
						new_umask |= new_val;
				}
				if (*cp == ',') {
					positions = 0;
					cp++;
				} else if (!strchr("=+-", *cp))
					break;
			}
			if (*cp) {
				bi_errorf("bad mask");
				return 1;
			}
			new_umask = ~new_umask;
		}
		umask(new_umask);
	}
	return 0;
}

int posh_builtin_unset(int argc, char **argv, int UNUSED(flags))
{
	char *id;
	int optc, unset_var = 1;
	int ret = 0;

	optind = 0;

	while ((optc = getopt(argc, argv, "fv")) != -1) {
		switch(optc) {
		  case 'f':
			unset_var = 0;
			break;
		  case 'v':
			unset_var = 1;
			break;
		  case '?':
			return 1;
		}
	}
	argv += optind;
	for (; (id = *argv) != NULL; argv++)
		if (unset_var) {	/* unset variable */
			struct tbl *vp = global(id);

			if ((vp->flag&RDONLY)) {
				bi_errorf("%s is read only", vp->name);
				return 1;
			}
			unset(vp, strchr(id, '[') ? 1 : 0);
		} else {		/* unset function */
			if (define(id, (struct op *) NULL))
				ret = 1;
		}
	return ret;
}

int posh_builtin_wait(int argc, char **argv, int UNUSED(flags))
{
	int UNINITIALIZED(rv);
	int sig, optc;
	char **wp;

	while ((optc = getopt(argc, argv, "")) != -1) {
		if(optc == '?')
			return 1;
	}
	wp = argv + optind;
	if (*wp == (char *) 0) {
		while (waitfor((char *) 0, &sig) >= 0)
			;
		rv = sig;
	} else {
		for (; *wp; wp++)
			rv = waitfor(*wp, &sig);
		if (rv < 0)
			rv = sig ? sig : 127; /* magic exit code: bad job-id */
	}
	return rv;
}

extern int posh_builtin_test ARGS((int, char **wp, int)); /* in c_test.c */
extern int posh_builtin_times(int argc, char **argv, int flags);

const struct builtin shbuiltins [] = {
	{".", posh_builtin_dot, POSH_BUILTIN_POSIX_SPECIAL | POSH_BUILTIN_KEEPASN},
	{":", posh_builtin_colon, POSH_BUILTIN_POSIX_SPECIAL | POSH_BUILTIN_KEEPASN},
	{"[", posh_builtin_test, 0},
	{"break", posh_builtin_brkcont, POSH_BUILTIN_POSIX_SPECIAL | POSH_BUILTIN_KEEPASN | POSH_BUILTIN_BREAK},
	{"builtin", posh_builtin_builtin, POSH_BUILTIN_KEEPASN},
	{"continue", posh_builtin_brkcont, POSH_BUILTIN_POSIX_SPECIAL | POSH_BUILTIN_KEEPASN | POSH_BUILTIN_CONTINUE},
	{"eval", posh_builtin_eval, POSH_BUILTIN_POSIX_SPECIAL | POSH_BUILTIN_KEEPASN},
	{"exec", posh_builtin_exec, POSH_BUILTIN_POSIX_SPECIAL | POSH_BUILTIN_KEEPASN},
	{"exit", posh_builtin_exitreturn, POSH_BUILTIN_POSIX_SPECIAL | POSH_BUILTIN_KEEPASN | POSH_BUILTIN_EXIT},
	{"false", posh_builtin_colon, POSH_BUILTIN_POSIX_REGULAR | POSH_BUILTIN_FALSE},
	{"return", posh_builtin_exitreturn, POSH_BUILTIN_POSIX_SPECIAL | POSH_BUILTIN_KEEPASN | POSH_BUILTIN_RETURN},
	{"set", posh_builtin_set, POSH_BUILTIN_POSIX_SPECIAL | POSH_BUILTIN_KEEPASN},
	{"shift", posh_builtin_shift, POSH_BUILTIN_POSIX_SPECIAL | POSH_BUILTIN_KEEPASN},
	{"times", posh_builtin_times, POSH_BUILTIN_KEEPASN},
	{"trap", posh_builtin_trap, POSH_BUILTIN_POSIX_SPECIAL | POSH_BUILTIN_KEEPASN},
	{"wait", posh_builtin_wait, POSH_BUILTIN_POSIX_REGULAR | POSH_BUILTIN_KEEPASN},
	{"read", posh_builtin_read, POSH_BUILTIN_POSIX_REGULAR},
	{"test", posh_builtin_test, 0},
	{"true", posh_builtin_colon, POSH_BUILTIN_POSIX_REGULAR},
	{"umask", posh_builtin_umask, POSH_BUILTIN_POSIX_REGULAR},
	{"unset", posh_builtin_unset, POSH_BUILTIN_POSIX_SPECIAL | POSH_BUILTIN_KEEPASN},

	{"cd", posh_builtin_cd, POSH_BUILTIN_POSIX_REGULAR},
	{"command", posh_builtin_command, POSH_BUILTIN_POSIX_REGULAR},
	{"echo", posh_builtin_echo, 0},
 	{"export", posh_builtin_exportreadonlyset, POSH_BUILTIN_POSIX_SPECIAL | POSH_BUILTIN_KEEPASN | POSH_BUILTIN_EXPORT},
	{"getopts", posh_builtin_getopts, POSH_BUILTIN_POSIX_REGULAR},
#if 0
	{"kill", posh_builtin_kill, POSH_BUILTIN_POSIX_REGULAR},
#endif
	{"local", posh_builtin_local, POSH_BUILTIN_KEEPASN},
	{"pwd", posh_builtin_pwd, 0},
 	{"readonly", posh_builtin_exportreadonlyset, POSH_BUILTIN_POSIX_SPECIAL | POSH_BUILTIN_KEEPASN | POSH_BUILTIN_READONLY},
	{NULL, NULL, 0}
};
