/* @(#)remove.c	1.42 01/07/12 Copyright 1985 J. Schilling */
#ifndef lint
static	char sccsid[] =
	"@(#)remove.c	1.42 01/07/12 Copyright 1985 J. Schilling";
#endif
/*
 *	remove files an file trees
 *
 *	Copyright (c) 1985 J. Schilling
 */
/*
 * 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, 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; see the file COPYING.  If not, write to
 * the Free Software Foundation, 675 Mass Ave, Cambridge, MA 02139, USA.
 */

#include <mconfig.h>
#include <stdio.h>
#include <standard.h>
#include "star.h"
#include "table.h"
#include <dirdefs.h>	/*XXX Wegen S_IFLNK */
#include <unixstd.h>
#include <schily.h>

#ifdef	JOS
#	include	<error.h>
#else
#	include	<errno.h>
#	define	EMISSDIR	ENOENT
#endif
#include "starsubs.h"


extern	FILE	*tty;
extern	BOOL	interactive;
extern	BOOL	force_remove;
extern	BOOL	ask_remove;
extern	BOOL	remove_first;
extern	BOOL	remove_recursive;

EXPORT	BOOL	remove_file	__PR((char* name, BOOL isfirst));

EXPORT BOOL
remove_file(name, isfirst)
	register char	*name;
		 BOOL	isfirst;
{
	char	buf[32];
	char	ans;
	int	err = EX_BAD;

	if (remove_first && !isfirst)
		return (FALSE);
	if (interactive || ask_remove) {
		printf("remove '%s' ? Y(es)/N(o) :", name);flush();
		fgetline(tty, buf, 2);
	}
	if (force_remove ||
	    ((interactive || ask_remove) && (ans = toupper(buf[0])) == 'Y')) {

		/*
		 * only unlink non directories or empty
		 * directories
		 * XXX need to implement the -remove-recursive flag
		 */
		if (rmdir(name) < 0) {
			err = geterrno();
			if (err == ENOTDIR) {
				if (unlink(name) < 0) {
					err = geterrno();
					goto cannot;
				}
				return (TRUE);
			}
#if defined(ENOTEMPTY) && ENOTEMPTY != EEXIST
			if (err == EEXIST || err == ENOTEMPTY) {
#else
			if (err == EEXIST) {
#endif
				if (!remove_recursive) {
					errmsgno(err,
					"Nonempty directory '%s' not removed.\n",
					name);
					return (FALSE);
				}
				
			}
			goto cannot;
		}
		return (TRUE);
	}
cannot:
	errmsgno(err, "File '%s' not removed.\n", name);
	return (FALSE);
}
