/* Unix-like "rm" command.

   Unix->Amiga pathname alteration:

	Translates ".", "..", "./" and "../" into Amiga parlance.
*/

#include <stdio.h>
#include <string.h>
#include "stat.h"
#include "dir.h"

int recurse = 0;
int force = 0;
int verbose = 0;		/* Non-standard */
extern char *optarg;
extern int optind;
char path[1024];
char *curp = path;

int unlink_file(char *f)
{
    if (force) chmod(f,0777);
    if (remove(f)) {
	fprintf (stderr, "rm: File \'%s\' - Can't remove.\n", f);
        return(1);
    }
    if (verbose)
	fprintf (stderr, "rm: File \'%s\' removed.\n", f);
    return(0);
}

main(int argc, char **argv)
{
    char *cp, *last, **cpp, **cppo, **wildexpand();
    int i, err = 0;

    while ((i = getopt(argc, argv, "frv")) != -1) {
	switch (i) {
	    case 'f':
		force++;
		break;
	    case 'r':
		recurse++;
		break;
	    case 'v':
		verbose++;
		break;
	    case '?':		/* can be no other kind of return */
		exit(1);
	}
    }
    for (; optind < argc; optind++) {
	if (!*(cp = argv[optind])) continue;
	amigaizepath(cp);
	if (*(last = &cp[strlen(cp) - 1]) == ':') {
	    fprintf(stderr, "rm: File \'%s\' -- Can't delete device.\n", cp);
	    continue;
	}
	for (i = 0; *last == '/'; i++, last--) {
	    *last = '\0';
	}
	if (!*cp || i > 1) {
	    fprintf(stderr, "rm: File \'%s\' -- Invalid '/'s at end.\n", cp);
	    continue;
	}

	cppo = wildexpand(cp);

	for (cpp = cppo; *cpp; cpp++)
	    err += deltree(*cpp);

	wildfree(cppo);
    }
    exit(err);
}

int deltree(char *f)
{
    DIR	*dirp;
    struct direct *dp;
    char *hold_curp = curp;
    int err = 0;
    struct stat stbuf;

    strcpy (curp, f);
    curp = path + strlen(path);
	
    if (stat (path, &stbuf) < 0) {
	fprintf(stderr, "rm: Can't stat file: %s\n", path);
	return(1);
    }
    if ((stbuf.st_mode & S_IFMT) == S_IFDIR && recurse) {
	if (!(dirp = opendir(path))) {
	    fprintf(stderr, "rm: Can't open directory: %s\n", path);
	    err++;
	} else {
	    *curp++ = '/';
	    while (dp = readdir(dirp)) {
		if (!(dp->d_ino)) continue;
		err += deltree(dp->d_name);
	    }
	    closedir(dirp);
	    *--curp = '\0';
	}
    }
    if (!err)
	err += unlink_file(path);
    curp = hold_curp;
    *curp = '\0';
    return(err);
}
