#

/*
 * status codes
 */
	/* Overall status */
#define		ALLGOOD	0
#define		SOMEBAD 4
#define		ALLBAD	-1
	/* Incremental status */
#define		GOOD	0
#define		BAD	4
#define		VBAD	-1
 
struct xcode{
	int summary;
	int count;
}xcode;

main(argc, argv)
char *argv[];
{
	char *arg;
	int fflg, rflg, ex;

	xcode.summary = ALLGOOD;
	xcode.count =   argc - 1;
	fflg = 0;
	rflg = 0;
	while(--argc > 0) {

		arg = *++argv;
		if(arg[0] == '-') {
			xcode.count--;
			if(arg[1] == 'f') {
				fflg++;
				continue;
			}
			if(arg[1] == 'r') {
				rflg++;
				continue;
			}
		}

		if((ex = rm(arg, fflg, rflg)) > GOOD) {
			xcode.count--;
			if(ex > xcode.summary) {
				xcode.summary = ex;
			}
		}
	}
	if(xcode.count == 0)
		exit(ALLBAD);
	else
		exit(xcode.summary);
}

struct stbuf	{
	int dev;
	int inum;
	int mode;
	char nlink;
	char uid;
	char gid;
	char siz0;
	char siz1;
	int addr[8];
	int adate[2];
	int mdate[2];
	};

rm(arg, fflg, rflg)
char arg[];
{
	char *p;
	int buf[20];
	int i, b;
	int status;
	int	ln;
	struct{
		char	lobyte;
		char	hibyte;
	};

	if(stat(arg, buf)) {
		printf("%s: non existent\n", arg);
		return(BAD);
	}
	if((buf->mode & 060000) == 040000)	{
		if(rflg) {
			i = fork();
			if(i == -1) {
				printf("%s: try again\n", arg);
				return(VBAD);
			}
			if(i) {
				while(wait(&status) != i);
				return(status >> 8);
			}
			if(chdir(arg)) {
				printf("%s: cannot chdir\n", arg);
				exit(BAD);;
			}
			p = 0;
			execl("/etc/glob", "glob", "rm", "-r",
				fflg? "-f": "*", fflg? "*": p, 0);
			printf("%s: no glob\n", arg);
			exit(VBAD);
		}
		printf("%s: directory\n", arg);
		return(BAD);
	}

	if(!fflg) {

		if((getuid()&0377) == buf->uid)
			b = 0200; else
			b = 2;
		ln = lnxx(0);
		if((buf->mode & b)==0 && (ln.lobyte!='x' || ln.hibyte!='x')){
			printf("%s: %o mode ", arg, buf->mode);
			i = b = getchar();
			i = b;
			while(b != '\n' && b != '\0')
				b = getchar();
			if(i != 'y')
				return(GOOD);
		}
	}
	if(unlink(arg)) {
		printf("%s: not removed\n", arg);
		return(BAD);
	}
	return(GOOD);
}

putchar(c)
{
	write(1, &c, 1);
}

getchar()
{
	char c;

	if(read(0, &c, 1) != 1) return(0);
	return(c);
}
