/*
**	rm [-fir] file ...
*/

#include	<stdio.h>
#include	<types.h>
#include	<stat.h>
#include	<dir.h>

int	errcode;



_main(argc, argv)
char *argv[];
{
	register char *arg;
	int fflg, iflg, rflg;

	fflg = 0;
	if (isatty(0) == 0)
		fflg++;
	iflg = 0;
	rflg = 0;
	while(argc>1 && argv[1][0]=='-') {
		arg = *++argv;
		argc--;

		/*
		 *  all files following a null option are considered file names
		 */
		if (*(arg+1) == '\0') break;

		while(*++arg != '\0')
			switch(*arg) {
			case 'f':
				fflg++;
				break;
			case 'i':
				iflg++;
				break;
			case 'r':
				rflg++;
				break;
			default:
				printf("rm: unknown option %s\n", *argv);
				exit(1);
			}
	}
	while(--argc > 0) {
		if(!strcmp(*++argv, "..")) {
			fprintf(stderr, "rm: cannot remove `..'\n");
			continue;
		}
		rm(*argv, fflg, rflg, iflg);
	}

	exit(errcode?2:0);
}


rm(arg, fflg, rflg, iflg)
char arg[];
{
	struct	stat	buf;
	struct	direct	direct;
	char	name[100];
	int	d;

	if(stat(arg, &buf)) {
		if (fflg==0) {
			fprintf(stderr, "rm: %s non-existent\n", arg);
			++errcode;
		}
		return;
	}
	if ((buf.st_mode&S_IFMT) == S_IFDIR) {
		if(rflg) {
			if(iflg && !dotname(arg)) {
				printf("directory %s: ? ", arg);
				if(!yes())
					return;
			}
			if((d=open(arg, 0)) < 0) {
				fprintf(stderr, "rm : cannot read %s\n", arg);
				exit(2);
			}
			while(read(d, &direct, sizeof(direct)) == sizeof(direct)) {
				if(direct.d_ino != 0 && !dotname(direct.d_name)) {
					sprintf(name, "%s/%.14s", arg, direct.d_name);
					rm(name, fflg, rflg, iflg);
				}
			}
			close(d);
			errcode += rmdir(arg, iflg);
			return;
		}
		fprintf(stderr, "rm: %s directory\n", arg);
		++errcode;
		return;
	}

	if(iflg) {
		printf("%s: ? ", arg);
		if(!yes())
			return;
	}
	else if(!fflg) {
		if(access(arg, 02) < 0 && isatty(fileno(stdin))) {
			printf("%s: %o mode ? ", arg, buf.st_mode&0777);
			if(!yes())
				return;
		}
	}
	if(unlink(arg) && (fflg==0 || iflg)) {
		fprintf(stderr, "rm: %s not removed.  ", arg);
		perror("");
		++errcode;
	}
}

dotname(s)
char *s;
{
	if((s[0]&0177) == '.')
		if((s[1]&0177) == '.')
			if(s[2] == '\0' || (s[2]&0177) == '/')
				return(1);
			else
				return(0);
		else if(s[1] == '\0')
			return(1);
	return(0);
}

rmdir(f, iflg)
char *f;
{
	extern char **environ;
	static char *argv[] = { "rmdir", 0, 0};

	int	status, i;

	if(dotname(f))
		return(0);
	if(iflg) {
		printf("%s: ? ", f);
		if(!yes())
			return(0);
	}
	while((i=fork()) == -1)
		sleep(3);
	if(i) {
		wait(&status);
		return(status);
	}
/*	execl("/bin/rmdir", "rmdir", f, 0); */
	argv[1] = f;
	execve("/bin/rmdir", argv, environ);
	printf("No rmdir\n");
	exit(2);
}

yes()
{
	int	i, b;

	i = b = getchar();
	while(b != '\n' && b > 0)
		b = getchar();
	return(i == 'y');
}
