/**********************************************************************
 
	Copyright (C) 2003 Hirohisa MORI <joshua@nichibun.ac.jp>
 
	This program is free software; you can redistribute it 
	and/or modify it under the terms of the GLOBALBASE 
	Library General Public License (G-LGPL) as published by 

	http://www.globalbase.org/
 
	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.

**********************************************************************/


#include	<stdlib.h>
#include	<string.h>
#include	"memory_debug.h"
#include	"utils.h"

int
unlink_p(char * path);

int
unlink_p(char * path)
{
int len;
char * _path;
int ret;
	len = strlen(path);
	if ( path[len-1] == '/' ) {
		_path = copy_str(path);
		_path[len-1] = 0;
		ret = u_unlink(_path);
		d_f_ree(path);
	}
	else	ret = u_unlink(path);
	return ret;
}

void
u_rm(char * path,int flags)
{
U_STAT st;
DIR * dd;
struct dirent * d;
char * buf;
int len;

	if ( flags & RMF_REC ) {
		u_stat(path,&st);
		switch (st.us_mode & S_IFMT) {
//		case S_IFREG:
		case S_IFDIR:
			dd = u_opendir(path);
			if ( dd == 0 )
				break;
			for ( ; ; ) {
				d = u_readdir(dd);
				if ( d == 0 )
					break;
				if ( strcmp(d->d_name,".") == 0 )
					continue;
				if ( strcmp(d->d_name,"..") == 0 )
					continue;
				buf = d_alloc(
					(len=strlen(path))+
					strlen(d->d_name)+10);
				strcpy(buf,path);
				if ( buf[len-1] == '/' )
					strcpy(&buf[len],d->d_name);
				else {
					buf[len] = '/';
					strcpy(&buf[len+1],d->d_name);
				}
				u_rm(buf,flags);
			}
			closedir(dd);

			rmdir(path);

			break;
		default:

			unlink_p(path);

			break;
		}
	}
	else {
		if ( flags & RMF_FILE ) {
			u_stat(path,&st);
			if ( (st.us_mode & S_IFMT) != S_IFDIR )
				unlink_p(path);
		}
		if ( flags & RMF_DIR ) {
			u_stat(path,&st);
			if ( (st.us_mode & S_IFMT) == S_IFDIR ) {
				dd = u_opendir(path);
				if ( dd == 0 ) {
					rmdir(path);
					goto no_rm;
				}
				for ( ; ; ) {
					d = u_readdir(dd);
					if ( d == 0 )
						break;
					if ( strcmp(d->d_name,".") == 0 )
						continue;
					if ( strcmp(d->d_name,"..") == 0 )
						continue;
					closedir(dd);
					goto no_rm;
				}
				closedir(dd);
				rmdir(path);
			}
		no_rm:
			;
		}
	}
}
